简体   繁体   English

如何自动写入和读取文件?

[英]How to automatically write and read from files?

I have a java application that has 3 ArrayList objects: items , customers and orders . 我有一个java应用程序,它有3个ArrayList对象: itemscustomersorders

I'm wondering how do I write these objects to a file when I close the application and then how do I read from the files when I start the application? 我想知道当我关闭应用程序时如何将这些对象写入文件,然后在启动应用程序时如何从文件中读取?

This was the code I was given to help me: 这是我给予的帮助我的代码:

//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();

I think I can figure out how to do this by clicking a button to read and write but I would like to know how to do it automatically. 我想我可以通过点击按钮进行读写来弄清楚如何做到这一点,但我想知道如何自动完成。 (When the program starts and ends). (当程序开始和结束时)。

To read the file at the start of the program, you can just put the reading code at the start. 要在程序开头读取文件,您只需将读取代码放在开头即可。

But to make sure it is saved when you exit your program from anywhere , you could use a shutdown hook : 但是为了确保在从任何地方退出程序时保存它,您可以使用关闭钩子

Runtime.getRuntime().addShutdownHook(new Thread(() -> {
    // Shutdown code here
}));

Which you register at the start of the program. 您在程序开始时注册的。 It gets called when the JVM shuts down. 它在JVM关闭时被调用。 By the doc: 通过文档:

The Java virtual machine shuts down in response to two kinds of events: Java虚拟机关闭以响应两种事件:

  • The program exits normally, when the last non-daemon thread exits or when the exit (equivalently, System.exit) method is invoked, or 当最后一个非守护程序线程退出或调用退出(等效,System.exit)方法时,程序正常退出,或者
  • 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. 响应于用户中断(例如,键入^ C)或系统范围的事件(例如用户注销或系统关闭),终止虚拟机。

Now at the start of your program you would do something like this: 现在在你的程序开始时你会做这样的事情:

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'
}

It is important to note that, because the shutdown hook is executed at the end of the program, it will write the eventual state of the config object. 重要的是要注意,因为在程序结束时执行了关闭钩子,它将写入配置对象的最终状态。 So changes that are made to 'config' during the program, are taken into account. 因此,考虑在程序期间对“配置”进行的更改。


For objects to be able to be written like this, they need to implement java.io.serializable and so do all of their fields. 对于能够像这样编写的对象,他们需要实现java.io.serializable ,所以他们的所有字段都是如此。 Except for fields that have the transient qualifier. 除具有transient限定符的字段外。

The config object might look something like this: 配置对象可能如下所示:

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;

    ...
}

You should use Java serialization system. 您应该使用Java 序列化系统。

Java provides a mechanism, called object serialization where an object can be represented as a sequence of bytes that includes the object's data as well as information about the object's type and the types of data stored in the object. Java提供了一种称为对象序列化的机制,其中对象可以表示为包含对象数据的字节序列,以及有关对象类型和对象中存储的数据类型的信息。

After a serialized object has been written into a file, it can be read from the file and deserialized that is, the type information and bytes that represent the object and its data can be used to recreate the object in memory. 将序列化对象写入文件后,可以从文件中读取并反序列化,即表示对象及其数据的类型信息和字节可用于在内存中重新创建对象。

Here is a link to the official Java documentation with a lot of examples. 是一个带有大量示例的官方Java文档的链接。

Now to do it automatically, you just have to put this types of instructions at the beginning of your program to read the file 现在自动执行此操作,您只需将这些类型的指令放在程序的开头即可读取文件

When you exit you can use the exemple of the answer above. 当你退出时,你可以使用上面答案的例子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM