Java 7 for Absolute Beginners

(nextflipdebug5) #1
CHAPTER 8 ■ WRITING AND READING FILES

} catch (IOException ioe) {
System.out.println("Couldn't read from a file called " + fileName);
}
// Convert our content to a String
// and write it out to the console
System.out.print(new String(content));
}
}


Let's examine that program. After doing what we already know how to do (finding a file), we first set
up a data structure (a byte array) to hold the content of the file. Then we set up a try-catch block to
handle the exceptions that can arise when working with files. We could handle both kinds of exceptions
by handling just Exception (the parent object of both FileNotFoundException and IOException), but then
we won’t know what went wrong. More detail (up to a point) is generally better when diagnosing a
problem.
Within our try-catch block, we create a stream object to hold the content of the file and then read
the content of the stream into our byte array. Then we close the stream. In this simple case, we don’t
need to close the stream. The JVM does that for us when the program exits. However, closing files as
soon as you can is a good habit to have. Each open file forces the operating system to provide an object
called a file handle. Enough open files can greatly degrade a computer's performance, crash your
program, or even crash the operating system.
After we have the contents of the file in memory, we can do something with it. In this case, we cast it
into a String object and send the String object to the console, thus mirroring the contents of our file. We
can potentially do many other things with the contents of a file. A word processing program would
display the content to the user so that the user can modify the content, a game might initialize certain
values (perhaps the size of the map and how aggressive the opponent is), and so on.


Writing a File's Content


Writing to a file works in much the same way as reading from a file. We get a stream, put the content we
want to write to the file in the stream, write that content to the file, and then close the stream. Listing 8-
14 shows a program that does just that. It’s a little more complex but still straight-forward. For fun and
so that we can be sure something happens when we compare the file before and after we run the
program, we reverse the file's content along the way.


Listing 8-14. Writing to hamlet.txt


package com.apress.java7forabsolutebeginners.examples;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;


public class WriteFile {

Free download pdf