Java Reference
In-Depth Information
The starting point for reading a file is to create a
FileInputStream
object. Creating
FileInputStream
objects is not very different from creating
FileOutputStream
objects so let's
look into how we do that first.
In our examples in this chapter we will be reading some of the files that we created in
the last chapter so I hope that you kept them.
Creating File Input Streams
Since a
FileInputStream
object encapsulates a file that is essentially intended to be read and
therefore must contain some data, a constructor for this class can only create an object for a file that
already exists. There are three constructors for
FileInputStream
objects, each of which takes a
single argument.
First of all you can create a
FileInputStream
object from a
String
object that specifies the file
name. For example:
FileInputStream inputFile = null; // Place to store the input stream reference
try {
inputFile = new FileInputStream("C:/Beg Java Stuff/myFile.txt");
} catch(FileNotFoundException e) {
e.printStackTrace(System.err);
System.exit(1);
}
The
try
block is necessary here because this constructor will throw a
FileNotFoundException
if
the file does not exist or the argument to the constructor specifies a directory rather than a file.
You could also use a
File
object to identify the file, like this:
File aFile = new File("C:/Beg Java Stuff/myFile.txt");
FileInputStream inputFile = null; //Place to store the input stream reference
try {
inputFile = new FileInputStream(aFile);
} catch(FileNotFoundException e) {
e.printStackTrace(System.err);
System.exit(1);
}
This constructor can also throw a
FileNotFoundException
so again we must create the
FileInputStream
object within a
try
block. Using a
File
object to create a
FileInputStream
object is the preferred approach because you can check that the file exists before creating the stream
and thus avoid the possibility of throwing a
FileNotFoundException
.