Dean Dean - 2 months ago 12
Java Question

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

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 the 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?

Answer

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)