Friday, May 6, 2011

Java File Save and File Load: Text

We've looked at saving and loading objects to files. If we need to exchange information for use by a different program than our own it will seldom be convenient to save objects. Text files are commonly used to do this.

Text files are even simpler to deal with than Object files, thanks to classes in the package. FileWriter gives us everything we need to write from our program to a text file. All we need to do is feed it String data.

FileReader lets us access a file, but using a BufferedReader makes it a lot easier to handle reading data from a file as lines of text.

As with object files, the basic steps are:
1. Open a file.
2. Write or read data.
3. Close the file.

Here are example programs, the first writes a simple text file. After you run it, you can take a look at the file it creates (in the same directory) using your favorite text viewer. You'll see normal text written line by line.

Then run the second program. It reads in the information line by line. It takes advantage of the fact that we know the format of the data file to read what's in it back into Java objects. You can do the same thing with any file that you either know the format of, or can detect the format of. For example, reading data from CSV files saved by spreadsheets (I'll provide a specific example of this in a future article.)

As always, you can download the program files from the Begin With Java Code Archive.


public class TextSave{

public static void main(String[] arg) throws Exception {
// Create some data to write.
int x=1, y=2, z=3;
String name = "Galormadron", race = "elf";
boolean hyperactive = true;

// Set up the FileWriter with our file name.
FileWriter saveFile = new FileWriter("TextSave.txt");

// Write the data to the file.
saveFile.write(x + "\n");
saveFile.write(y + "\n");
saveFile.write(z + "\n");
saveFile.write(name + "\n");
saveFile.write(race + "\n");
saveFile.write(Boolean.toString(hyperactive) + "\n");

// All done, close the FileWriter.

} //main()
} // TextSave


public class TextRead{

public static void main(String[] arg) throws Exception {
int x, y, z;
String name = "", race = "";
boolean hyperactive;

BufferedReader saveFile=
new BufferedReader(new FileReader("TextSave.txt"));

// Throw away the blank line at the top.
// Get the integer value from the String.
x = Integer.parseInt(saveFile.readLine());
y = Integer.parseInt(saveFile.readLine());
z = Integer.parseInt(saveFile.readLine());
name = saveFile.readLine();
race = saveFile.readLine();
hyperactive = Boolean.parseBoolean(saveFile.readLine());
// Not needed, but read blank line at the bottom.


// Print out the values.
System.out.println("x=" + x + " y=" + y + " z=" + z + "\n");
System.out.println("name: " + name + " race: " + race + "\n");
if (hyperactive)
System.out.println("Oh, yeah. He's hyperactive all right.");
else System.out.println("What a mellow dude.");

} //main()
} // TextRead