我正在处理文件中的序列化和反序列化。此外,我正在研究将 FileOutputStream
与 ObjectOutputStream
结合使用。问题是我有服务器/客户端聊天应用程序,每当客户端连接时,服务器必须检查连接的客户端之前是否已注册。因此,当客户端连接到服务器时,服务器会创建一个输出流,如
FileOutputStream fos = new FileOutputStream("src\\example\\mainList.txt");
得到一个链表来检查这个链表是否包含这个对象。但是,FileOutputStream
总是创建一个没有内容的新文件。我知道如果我将“真”值作为第二个参数传递给追加文件,但是这个 .txt 文件应该只包含一个对象,它是一个链表。因此,我不想在每个进程中附加一个列表。我该如何处理问题?我只是想要
- 如果有没有内容的指定文件不读取对象,只添加第一次列表
- 如果有指定文件的内容(意味着只有一个链表对象)则读取它,并将新客户端添加到列表中并将链表对象写回到文件中。
我希望您已经清楚地了解了我的问题,我将不胜感激您的每一个回答。所以还是谢谢
编辑:这是我想说的一个简单例子。
public class PersonTest2 {
public static void main(String[] args) throws IOException, ClassNotFoundException {
LinkedList<Person> list = new LinkedList<Person>();
Person per = new Person("John","Thompson",22);
Person per2 = new Person("Suzie","Cash",23);
Person per3 = new Person("Peter","Jackson",24);
Person per4 = new Person("Michael","Coch",25);
list.add(per);
list.add(per2);
list.add(per3);
list.add(per4);
FileOutputStream fos = new FileOutputStream("person.txt");
BufferedReader br = new BufferedReader(new FileReader("person.txt"));
if (br.readLine() == null ) {
System.out.println("No errors, and file is empty");
}
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(list);
fos.close();
FileInputStream fis = new FileInputStream("person.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
LinkedList<Person> list2;
list2 = (LinkedList) ois.readObject();
for (Iterator<Person> itr = list2.iterator(); itr.hasNext();) {
Person rper = itr.next();
System.out.println(rper.name + " " + rper.last_name + " " + rper.age);
}
}
}
每次我运行这段代码时,FileOutputStream 都会打开一个新文件。但是,如果我使用 true
作为第二个参数,它将附加链表。
最佳答案
- If there is speficied file with no contents don't read object, just add the list for only first time
- If there is the specified file with contents (mean that there is only one linkedlist object) then read it, and add the new client into the list and write the linkedlist object back into the file.
您可以通过以下方式执行此操作:
File file = new File("person.txt");
boolean toWrite = false;
boolean toModify = false;
if (file.exists())
{
if (file.length() == 0)
{
toWrite = true;
}
else
{
toModify = true;
}
}
if (toWrite || !file.exists())
{
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(list);
fos.close();
oos.close();
}
else if (toModify)
{
FileInputStream fins = new FileInputStream(file);
ObjectInputStream oins = new ObjectInputStream(fins);
LinkedList<Person> temp = (LinkedList<Person>)oins.readObject();
fins.close();
oins.close();
temp.add(per);
temp.add(per2);
temp.add(per3);
temp.add(per4);
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(temp);
fos.close();
oos.close();
}
关于java - FileOutputStream 打开一个新文件并在创建时删除内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15599137/