4

I have a java application that has 3 ArrayList objects: items, customers and orders.

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).

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • 4
    Possible duplicate of [Java - How Can I Write My ArrayList to a file, and Read (load) that file to the original ArrayList?](http://stackoverflow.com/questions/16111496/java-how-can-i-write-my-arraylist-to-a-file-and-read-load-that-file-to-the) – Darren Apr 26 '16 at 09:31
  • 1
    I have issues understanding your question... What do you mean by "when the program starts and ends" If you want to to some load&save operations why don't you just implement them at the start & at the end of the program? – ParkerHalo Apr 26 '16 at 09:32
  • @ParkerHalo Oh so all i have to do is put the code at the start of the program? I thought there was a type of syntax to have it start automatically when the program starts and for it to save right as i close the program – shawnmurray1337 Apr 26 '16 at 09:43
  • @shawnmurray1337 it really depends on what you're trying to do, but if you want to load something from a file before using any other code, then yes, you just insert the code at the start/beginning of your program – ParkerHalo Apr 26 '16 at 09:45
  • @ParkerHalo Yes when i start the program i want the arraylists to be populated with the content saved in the file. I think doing this automatically is the best way. I will try to just put the code at the start and end. Thank you – shawnmurray1337 Apr 26 '16 at 09:50
  • Perhaps PCollections is what you need? http://pcollections.org/ – tbsalling Apr 26 '16 at 13:02

2 Answers2

2

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. By the doc:

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.

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. Except for fields that have the transient qualifier.

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;

    ...
}
Jorn Vernee
  • 31,735
  • 4
  • 76
  • 93
1

You should use Java serialization system.

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.

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.

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.

Community
  • 1
  • 1
Mxsky
  • 749
  • 9
  • 27