是否可以通过不同的方法写入同一个文件?
我有以下方法:
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();
}
但我想知道是否可以用另一个数组列表再次写入文件 minos.dat ?例如,有另一种方法是这样的:
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();
}
我能够检索时间数组列表和参赛者吗?或者我需要写入单独的文件吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
可以,但如果您不想覆盖文件的内容,而只想追加,请像这样打开它:(
使用 此构造函数)
You can, but if you don't want to override the content of the file, but only append, open it like that:
(using this constructor)
如果您的意思是在一个线程中顺序进行,那么您使用@MByD 解决方案。它称为追加。如果这是多线程的,那么您将需要阻塞和同步。
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.
不适用于对象流。如果没有特殊措施,您无法使用对象输出流附加到文件。您必须:
ObjectOutputStream
Not in the case of object streams. Without special measures you cannot append to a file using object output streams. You must:
ObjectOutputStream
for the life of the process