我有一个 java 应用程序有 3 ArrayList
对象:items
, customers
和 orders
.
我想知道如何在关闭应用程序时将这些对象写入文件,然后在启动应用程序时如何从文件中读取?
这是我得到的帮助我的代码:
//Write to file
ObjectOutputStream outputStream;
outputStream=new ObjectOutputStream(new FileOutputStream("customerFile",true));
outputStream.writeObject(customers);
outputStream.close();
//Read from file
Clients fileCust = null;
ObjectInputStream inputStream;
inputStream = new ObjectInputStream(new FileInputStream("customerFile"));
fileCust = (Clients)inputStream.readObject();
inputStream.close();
我想我可以通过单击按钮进行读写来弄清楚如何执行此操作,但我想知道如何自动执行此操作。 (程序开始和结束时)。
最佳答案
要在程序开始读取文件,只需将读取代码放在开始即可。
但是要确保在您从任何地方 退出程序时保存它,您可以使用shutdown hook。 :
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
// Shutdown code here
}));
您在程序开始时注册的。它在 JVM 关闭时被调用。通过文档:
The Java virtual machine shuts down in response to two kinds of events:
- The program exits normally, when the last non-daemon thread exits or when the exit (equivalently, System.exit) method is invoked, or
- The virtual machine is terminated in response to a user interrupt, such as typing ^C, or a system-wide event, such as user logoff or system shutdown.
现在在你的程序开始时你会做这样的事情:
public static void main(String... args) {
// getConfig() returns a configuration object read from a file
// Or a new object if no file was found.
Configuration config = getConfig();
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
...
// Note that I'm not appending to, but overwriting the file
ObjectOutputStream outputStream =
new ObjectOutputStream(new FileOutputStream("myConfigFile"));
outputStream.writeObject(config); // write the config object.
...
}));
// Rest of the program, using 'config'
}
需要注意的是,因为关闭 Hook 是在程序结束时执行的,所以它会写入配置对象的最终状态。因此,在程序期间对“配置”所做的更改将被考虑在内。
为了能够像这样编写对象,它们需要实现 java.io.serializable
并且它们的所有字段也是如此。具有 transient
限定符的字段除外。
配置对象可能看起来像这样:
public class Configuration implements java.io.Serializable {
// transient -> Will not be written or read.
// So it is always 'null' at the start of the program.
private transient Client lastClient = null;
// 'Client' must also implement java.io.serializable,
// for 'Configuration' to be serializable.
// Otherwise, an exception is thrown when writing the object.
private List<Client> clients = new ArrayList<Client>();
// 'String' already implements java.io.serializable.
private String someString;
...
}
关于java - 如何自动写入和读取文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36860684/