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

标签 java string serialization fileinputstream fileoutputstream

<分区>

我需要在 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());

最佳答案

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

new FileOutputStream(file, true)

Creates a file output stream to write to the file represented by the specified File object. If the second argument is true, then bytes will be written to the end of the file rather than the beginning. A new FileDescriptor object is created to represent this file connection.

但是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();
}

关于java - 使用 ObjectOutputStream 写入文件而不覆盖旧数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20261986/

相关文章:

java - 使用批处理文件启动 java 程序时隐藏控制台窗口?

java - 将 ArrayList 中创建的对象传递给另一个类的另一个方法

java - 为什么Spring MVC会以404响应并报告“在DispatcherServlet中未找到带有URI […]的HTTP请求的映射”?

java - 在 Android 上使用 List<String> 发出警告

Java 未经检查或不安全操作消息

java - 读取已通过gson库序列化的嵌套json对象

java - Tomcat Web 应用程序 - 将对象存储为用户定义的对象或简单的 ID 以通过服务器重新启动来保持用户 session ?

java - JDialog中的垂直滚动 Pane 问题

linux - 在多个服务器的 Linux 中搜索多个目录中的字符串

r - 在 R 中的字符串中不存在的数据框中创建列