Recall that a File object encapsulates the properties of a file or a path , but does not contain the methods for reading/writing data from/to a file. In order to perform I/O, you need to create objects using appropriate Java I/O classes. The objects contain the methods for reading/writing data from/to a file. For example, to write text to a file named temp.txt , you may create an object using the PrintWriter class, as follows :
PrintWriter output = new PrintWriter( "temp.txt" );
You can now invoke PrintWriter from the object to write a string into the file. For example, the following statement writes "Java 101" to the file:
output.print( "Java 101" );
The next statement closes the file.
output.close();
There are many I/O classes for various purposes. In general, these can be classified as input classes and output classes. An input class contains the methods to read data, and an output class contains the methods to write data. PrintWriter is an example of an output class, and Scanner is an example of an input class. The following code shows an example of creating an input object for the file temp.txt and reading data from the file:
Scanner input = new Scanner( new File( "temp.txt" )); System.out.println(input.nextLine());
If temp.txt contains "Java 101" , input.nextLine() returns string "Java 101" .
Figure 18.1 illustrates Java I/O programming. An input object reads a stream of data from a file, and an output object writes a stream of data to a file. An input object is also called an input stream , and an output object is also called an output stream .