开发者

Is it possible to write to the same file from different methods?

开发者 https://www.devze.com 2023-03-17 17:10 出处:网络
I have the following method: public static void writeContestantsToFile(ArrayList<Contestant> contestants) throws IOException {

I have the following method:

public static void writeContestantsToFile(ArrayList<Contestant> contestants) throws IOException {
    FileOutputStream fos = new FileOutputStream("minos.dat");
    ObjectOutputStream oos = new ObjectOutputStream(fos);

    oos.writeObject(contestants);
    oos.flush();
    oos.close();
}

But I am wondering whether or not I can write to t开发者_如何转开发he file minos.dat again with another arraylist? For example have another method like this:

public static void writeContestantsToFile(ArrayList<Times> times) throws IOException {
    FileOutputStream fos = new FileOutputStream("minos.dat");
    ObjectOutputStream oos = new ObjectOutputStream(fos);

    oos.writeObject(times);
    oos.flush();
    oos.close();
}

Will I be able to retrieve both the times arraylist and contestants? Or do I need to write to separate files?


You can, but if you don't want to override the content of the file, but only append, open it like that:

FileOutputStream fos = new FileOutputStream("minos.dat", true);

(using this constructor)


If you mean sequentially in one thread then you use @MByD solution. Its called appending. If this is multithreaded then you will need to block and synchronize.


Not in the case of object streams. Without special measures you cannot append to a file using object output streams. You must:

  • leave the file open
  • synchronize access to it
  • use the same ObjectOutputStream for the life of the process
  • and ensure it is closed when you exit.
0

精彩评论

暂无评论...
验证码 换一张
取 消