使用ObjectOutputStream写入文件而不覆盖旧数据

我需要在eclipse上的文件上编写字符串而不覆盖旧字符串。 该函数类似于:创建一个字符串,将其保存在文件中,创建另一个字符串,将其保存在文件中,这包含多个字符串。

字符串具有下一种格式:

String one = name surname surname; value1 value2 value3; code 

所以方法将是:创建字符串,将其保存在文件中。 创建另一个字符串,将其保存在文件上等。然后在文件上保存所需的字符串数量后,我需要读取列出控制台上所有字符串的文件。

但是现在,我只能在文件上保存一个字符串然后列出它。 如果我保存两个字符串,第二个会覆盖第一个字符串,无论如何,它不正确,因为当我想列出它们时返回null值。

这是在文件写入字符串的方法:

 public void writeSelling(List wordList) throws IOException { fileOutPutStream = new FileOutputStream (file); write= new ObjectOutputStream (fileOutPutStream); for (String s : wordList){ write.writeObject(s); } write.close(); } 

这就是我在主类上调用write方法的方法

  List objectlist= new ArrayList(); objectlist.add(product); //Product is the string I save each time //which has the format I commented above writeSelling(objectlist); 

这是从文件读取字符串的方法:

 public ArrayList readSelling() throws Exception, FileNotFoundException, IOException { ArrayList objectlist= new ArrayList(); fileInPutStream = new FileInputStream (file); read= new ObjectInputStream (fileInPutStream); for (int i=0; i<contador; i++){ objectlist.add(read.readObject()); } read.close(); return objectlist; } 

这就是我在主类上调用read的方式

 ArrayList sellingobjects; sellingobjects= readSelling(); for (Iterator it = sellingobjects.iterator(); it.hasNext();) { String s = (String)it.next(); } System.out.println(s.toString()); 

您应该打开这样的文件,以便在文件中附加字符串

 new FileOutputStream(file, true) 

创建文件输出流以写入由指定的File对象表示的文件。 如果第二个参数为true,则字节将写入文件的末尾而不是开头。 创建一个新的FileDescriptor对象来表示此文件连接。

但Java序列化不支持“追加”。 您无法将ObjectOutputStream写入文件,然后在追加模式下再次打开该文件并向其写入另一个ObjectOutputStream 。 你必须每次都重写整个文件。 (即,如果要将对象添加到文件中,则需要读取所有现有对象,然后使用所有旧对象再次写入文件,然后再写入新对象)。

我想你会使用DataOutputStream

 public void writeSelling(List wordList) throws IOException { fileOutPutStream = new FileOutputStream (file,true); DataOutputStream write =new DataOutputStream(fileOutPutStream); for (String s : wordList){ d.writeUTF(s); } write.close(); }