【问题标题】:write object to file java将对象写入文件java
【发布时间】:2012-03-07 18:37:42
【问题描述】:

我正在创建一个管理议程的应用程序。每个联系人都必须写入目标文件。如何检查文件是否存在以及有没有办法在不覆盖的情况下写入下一个对象??

我的班级:

import java.io.*;

public class WriteFile {
    public void setContact(Agenda contact){
        ObjectOutputStream out;

        try{
            File file = new File("Contacts.txt");
            out = new ObjectOutputStream(new FileOutputStream(file));
            out.writeObject(contact);


            out.flush();
            out.close();
            System.out.println("Object written to file");
        }
        catch (FileNotFoundException ex) {
            System.out.println("Error with specified file") ;
            ex.printStackTrace();
        }
        catch (IOException ex) {
            System.out.println("Error with I/O processes") ;
            ex.printStackTrace();
        }             
    }

}

【问题讨论】:

    标签: java file-io bufferedreader


    【解决方案1】:

    使用您的代码,我相信最简单的方法是使用 file.exists() 方法来检查文件是否存在。

    boolean exists = file.exists();
    

    那么你可以为 FileOutputStream 使用下面的构造函数:

    public FileOutputStream(File file, boolean append) throws FileNotFoundException
    

    追加到文件的末尾。显然,该对象的构造应该包含在 if-else 子句中,具体取决于 file.exists() 的值。

    【讨论】:

      【解决方案2】:

      使用file.exists() 检查文件是否存在。

      如果是,则从文件中读取旧数据,然后将旧数据和新数据写入临时文件。删除旧文件并将临时文件重命名为“Contacts.txt”。

      【讨论】:

        【解决方案3】:

        首先,可以写入的对象必须是实现了 Serializable 接口的类的实例,该接口没有要实现的方法,它只是一个标志,表明它的实例可以被序列化。

        秒数写入,或者不覆盖旧数据,在你的代码中使用这个:

        out = new ObjectOutputStream(new FileOutputStream(file), true);
        

        后座有一个“真”,使其附加,。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-05-15
          • 2015-07-09
          • 2013-10-04
          相关资源
          最近更新 更多