简体   繁体   English

将对象写入文件java

[英]write object to file java

I am creating an application that manages an agenda. 我正在创建一个管理议程的应用程序。 Each contact must be written in the object file. 每个联系人必须写在目标文件中。 How can I check if the file exists and is there a way to write the next object without overwriting?? 我如何检查文件是否存在以及是否有办法在不覆盖的情况下写入下一个对象?

My class: 我的课:

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

}

Use file.exists() to check if a file exists. 使用file.exists()检查文件是否存在。

If it does, read in the old data from the file then write the old data and the new data to a temporary file. 如果是这样,请从文件中读取旧数据,然后将旧数据和新数据写入临时文件。 Delete the old file and rename the temp file to 'Contacts.txt'. 删除旧文件,然后将临时文件重命名为“ Contacts.txt”。

Using your code, I believe the easiest thing to do would be to make use of the file.exists() method to check to see if the file exists. 使用您的代码,我相信最简单的方法是利用file.exists()方法检查文件是否存在。

boolean exists = file.exists();

Then you can use the following constructor for the the FileOutputStream: 然后,可以对FileOutputStream使用以下构造函数:

public FileOutputStream(File file, boolean append) throws FileNotFoundException

to append to the end of the file. 追加到文件末尾。 Obviously the construction of that object should be wrapped in an if-else clause, depending on the value of the file.exists(). 显然,根据file.exists()的值,该对象的构造应包含在if-else子句中。

first, object in which able to be written have to be an instance of a class which implements Serializable interface, that interface has no method to be implemented, it's just a flag which tell that it's instaces are can be serialized. 首先,要写入的对象必须是实现Serializable接口的类的实例,该接口没有要实现的方法,只是一个标志,表明可以将其实例化。

second to make writing countinously, or not overwrite the old data, use this in your code: 其次,进行繁琐的编写,或者不覆盖旧数据,请在代码中使用以下代码:

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

there is a 'true' at the back seat, to make it appends,. 后座上有一个“ true”,以使其为附加值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM