[英]How to automatically write and read from files?
我有一個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();
我想我可以通過點擊按鈕進行讀寫來弄清楚如何做到這一點,但我想知道如何自動完成。 (當程序開始和結束時)。
要在程序開頭讀取文件,您只需將讀取代碼放在開頭即可。
但是為了確保在從任何地方退出程序時保存它,您可以使用關閉鈎子 :
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
// Shutdown code here
}));
您在程序開始時注冊的。 它在JVM關閉時被調用。 通過文檔:
Java虛擬機關閉以響應兩種事件:
- 當最后一個非守護程序線程退出或調用退出(等效,System.exit)方法時,程序正常退出,或者
- 響應於用戶中斷(例如,鍵入^ C)或系統范圍的事件(例如用戶注銷或系統關閉),終止虛擬機。
現在在你的程序開始時你會做這樣的事情:
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'
}
重要的是要注意,因為在程序結束時執行了關閉鈎子,它將寫入配置對象的最終狀態。 因此,考慮在程序期間對“配置”進行的更改。
對於能夠像這樣編寫的對象,他們需要實現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 序列化系統。
Java提供了一種稱為對象序列化的機制,其中對象可以表示為包含對象數據的字節序列,以及有關對象類型和對象中存儲的數據類型的信息。
將序列化對象寫入文件后,可以從文件中讀取並反序列化,即表示對象及其數據的類型信息和字節可用於在內存中重新創建對象。
這是一個帶有大量示例的官方Java文檔的鏈接。
現在自動執行此操作,您只需將這些類型的指令放在程序的開頭即可讀取文件
當你退出時,你可以使用上面答案的例子。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.