Saving Data to Files with Java
Saving objects to a file in Java has a few steps to it, but it's pretty easy. We open a file to write to, create a "stream" for putting objects into the file, write the objects to that stream to put them in the file, then close the stream and file when we're done.
To reiterate:
1. Open a file.
2. Open an object stream to the file.
3. Write the objects to that stream.
4. Close the stream and file.
1. Opening the File
To open a file for writing, we use a FileOutputStream object. When we construct the new FileOutputStream, we give it a file name to open. If the file name exists, it opens the existing file. Otherwise, it creates a new file. To keep things simple, we're not going to check for a file existing here, or anything like that.
Example:
FileOutputStream saveFile = new FileOutputStream("saveFile.sav");
2. Open an Object Stream
To write objects to the FileOutputStream, we create an ObjectOutputStream. We give it the FileOutputStream object we've set up when we construct the new ObjectOutputStream object.
Example:
ObjectOutputStream save = ObjectOutputStream(saveFile);
3. Write Objects
When we write objects to the ObjectOutputStream, they are sent out through it to the FileOutputStream and into the file.
Example:
save.writeObject(objectToSave);
4. Close Up
When we close the ObjectOutputStream, it'll also close our FileOutputStream for us, so this is just one step.
Example:
save.close();
Example Program:
import java.io.*; import java.util.ArrayList; public class SaveObjects{ public static void main(String[] arg){ // Create some data objects for us to save. boolean powerSwitch=true; int x=9, y=150, z= 675; String name="Galormadron", setting="on", plant="rutabaga"; ArrayListstuff = new ArrayList (); stuff.add("One"); stuff.add("Two"); stuff.add("Three"); stuff.add("Four"); stuff.add("Five"); try{ // Catch errors in I/O if necessary. // Open a file to write to, named SavedObj.sav. FileOutputStream saveFile=new FileOutputStream("SaveObj.sav"); // Create an ObjectOutputStream to put objects into save file. ObjectOutputStream save = new ObjectOutputStream(saveFile); // Now we do the save. save.writeObject(powerSwitch); save.writeObject(x); save.writeObject(y); save.writeObject(z); save.writeObject(name); save.writeObject(setting); save.writeObject(plant); save.writeObject(stuff); // Close the file. save.close(); // This also closes saveFile. } catch(Exception exc){ exc.printStackTrace(); // If there was an error, print the info. } } }
Reading Data Files with Java
Now we need to know how to get data back from a file with Java. Since the data objects were stored using an ObjectOutputStream, they are saved in a way that makes them easy to read back using an ObjectInputStream.
There's one problem with ObjectImputStream, however. It doesn't return objects of the specific classes that they were originally. It just returns generic Objects. To get things back into their original class, we have to cast them into that type. Usually that means we need to know what their class was when they were written. It's possible to save class information along with the data, but in this case we just assume that we're reading back a file we have written, so we already know what class everything should be. I'll go into the details of reading other files in another article.
The steps are practically the same as for writing objects to a file:
1. Open a file.
2. Open an object stream from the file.
3. Read the objects to that stream.
4. Close the stream and file.
1. Opening the File
To open a file for reading, we use a FileInputStream object. When we construct the new FileIntputStream, we give it a file name to open. If the file name exists, it opens the existing file. Otherwise, we get an error which will print out a nastygram when we get to our catch statement. To keep things simple, we're not going to check for a file existing here.
Example:
FileInputStream saveFile = new FileInputStream("saveFile.sav");
2. Open an Object Stream
To read objects to the FileInputStream, we create an ObjectInputStream. We give it the FileInputStream object we've set up when we construct the new ObjectInputStream.
Example:
ObjectInputStream restore = ObjectInputStream(saveFile);
3. Read Objects
When we read objects from the ObjectInputStream, it gets then from the file.
Example:
Object obj = restore.readObject();
3 and a half. Cast Back to Class
Step 3. only restores a generic Object. If we know the original class, we should cast the Object back to its original class when we read it. If we had stored a String object, we'd read it something like this:
String name = (String) restore.readObject();
4. Close Up
When we close the ObjectInputStream, it'll also close our FileInputStream for us, so this is just one step.
Example:
restore.close();
Here's an example program to read back information saved by the first example program:
import java.io.*; import java.util.ArrayList; public class RestoreObjects{ public static void main(String[] arg){ // Create the data objects for us to restore. boolean powerSwitch=false; int x=0, y=0, z=0; String name="", setting="", plant=""; ArrayListstuff = new ArrayList (); // Wrap all in a try/catch block to trap I/O errors. try{ // Open file to read from, named SavedObj.sav. FileInputStream saveFile = new FileInputStream("SaveObj.sav"); // Create an ObjectInputStream to get objects from save file. ObjectInputStream save = new ObjectInputStream(saveFile); // Now we do the restore. // readObject() returns a generic Object, we cast those back // into their original class type. // For primitive types, use the corresponding reference class. powerSwitch = (Boolean) save.readObject(); x = (Integer) save.readObject(); y = (Integer) save.readObject(); z = (Integer) save.readObject(); name = (String) save.readObject(); setting = (String) save.readObject(); plant = (String) save.readObject(); stuff = (ArrayList ) save.readObject(); // Close the file. save.close(); // This also closes saveFile. } catch(Exception exc){ exc.printStackTrace(); // If there was an error, print the info. } // Print the values, to see that they've been recovered. System.out.println("\nRestored Object Values:\n"); System.out.println("\tpowerSwitch: " + powerSwitch); System.out.println("\tx=" + x + " y=" + y + " z=" + z); System.out.println("\tname: " + name); System.out.println("\tsetting: " + setting); System.out.println("\tplant: " + plant); System.out.println("\tContents of stuff: "); System.out.println("\t\t" + stuff); System.out.println(); // All done. } }
<<Return to How to Save to a File with Java
The example programs can be downloaded at:
Begin With Java Code Downloads