【问题标题】:Write to file using ObjectOutputStream without overwriting old data [duplicate]使用 ObjectOutputStream 写入文件而不覆盖旧数据 [重复]
【发布时间】:2013-12-14 05:55:36
【问题描述】:

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

字符串具有以下格式:

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

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

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

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

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

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

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

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

public ArrayList<Object> readSelling() throws Exception, FileNotFoundException, IOException {
    ArrayList<Object> objectlist= new ArrayList<Object>();
    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());

【问题讨论】:

  • 别告诉我你在 google 上搜索过“java write at the end of a file”,我不会相信你。
  • 我尝试在文件末尾写入,但没有正确读取字符串。我从java开始,对不起,如果对你来说是一件容易的事。我不明白为什么要投反对票,如果这应该是人们提出疑问和学习的地方

标签: java string serialization fileinputstream fileoutputstream


【解决方案1】:

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

new FileOutputStream(file, true)

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

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

我建议你使用DataOutputStream

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

【讨论】:

  • 我已经尝试过了,但没有读取我写的新字符串,而是读取了之前的字符串。我必须对new FileInputStream(file, true) 做同样的事情吗?
  • @masmic_87 不,你不能那样做。
  • 好的,即使我把true 放在那里,它也不能正确写入/读取,如果我写一个字符串,读取我以前的字符串,而不是新的。如果我写第二个,抛出这个:Error reading the file invalid type code: AC
  • 你能编辑你的帖子,在我的代码中添加这个修改吗?如果你能做到这一点,我将不胜感激,因为我在这一点上被阻止了。
  • 正如我之前告诉过你的,你能修改我的代码并将其添加到你的答案中吗?我是java的新手,即使我明白你的意思,我不知道该怎么做
猜你喜欢
  • 1970-01-01
  • 2023-03-28
  • 2012-04-15
  • 2011-05-08
  • 1970-01-01
  • 2012-06-18
  • 1970-01-01
  • 2012-04-24
  • 2012-12-09
相关资源
最近更新 更多