简体   繁体   English

用二进制文件读写和保存序列化对象

[英]reading writing and saving serialized objects with a binary file

I am working on a project in which I want the user to be able to input Objects into an ArrayList, close the program, and be able to open the program again and have the previous ArrayList (from the first run) accessible to the user.我正在做一个项目,我希望用户能够将对象输入到 ArrayList 中,关闭程序,并能够再次打开程序并让用户可以访问以前的 ArrayList(从第一次运行开始)。

I currently have the user input objects into an ArrayList, the list serializes and saves the ArrayList as a .bin file.我目前将用户输入对象放入 ArrayList,列表将 ArrayList 序列化并保存为 .bin 文件。 When I run the program again, the previous list is saved but when I enter new values, it overrides the old list.当我再次运行程序时,以前的列表被保存,但是当我输入新值时,它会覆盖旧列表。 I guess what I am looking for is a way to see if my .bin file exists, and if it does, add new objects to the ArrayList, and if it doesn't, create a new one.我想我正在寻找一种方法来查看我的 .bin 文件是否存在,如果存在,则将新对象添加到 ArrayList,如果不存在,则创建一个新对象。 I'll add some sample code below.我将在下面添加一些示例代码。

Here I create the arraylist and a string for which the .bin file is created.在这里,我创建了 arraylist 和一个为其创建 .bin 文件的字符串。

public class Tender {
ArrayList<Alcohol> arraylist = new ArrayList<Alcohol>();
String dataList = "dataList.bin";
}

Here is where I serialize the ArrayList.这是我序列化 ArrayList 的地方。

    private void Serialize() throws IOException {
         try (ObjectOutputStream os = new ObjectOutputStream(new  FileOutputStream(dataList))) {
             os.writeObject(arraylist);
             os.close();

             System.out.println("done writing");
         }
     }

And here is where I try to load back the serialized file from the previous run.这里是我尝试从上一次运行中加载回序列化文件的地方。

private void load() throws FileNotFoundException, IOException, ClassNotFoundException {
    try (ObjectInputStream is = new ObjectInputStream(new FileInputStream(dataList))) {
        ArrayList newAL;
        newAL = (ArrayList) is.readObject();
        System.out.println(newAL);
    }
    Start();
}
}

The way to see if the file exists is to try to open it, and catch the FileNotFoundEzception that occurs if it isn't there.查看文件是否存在的方法是尝试打开它,并捕获在它不存在时发生的FileNotFoundEzception If it's there, read the list;如果它在那里,请阅读列表; if it isn't, create a new one.如果不是,请创建一个新的。

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

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