|
The java.io package provides input and output streams that enable the programmer to read data from and write data to various sources. Unsurprisingly, the FileReader class allows the programmer to read character data from a file. The Scanner is significantly more useful for processing text as it enables you to read data a line at a time from a file. Similarly, the FileWriter class allows you to write data to a file a character at a time, while the PrintWriter supports the println operation, the same method you call when you output text to the standard output (e.g., System.out.println("Hello")), Take a look at the example below and notice the following:Importing the java.io PackageIn order to use the classes provided in the java.io package, you must import them. Recall that using "*" (e.g., import java.io.*;) will import all of the classes in a particular package. Wrapping StreamsCreating input and output streams requires several steps. In order to create a PrintWriter you must first create a FileWriter, the constructor of which takes as input a file name. ExceptionsMost of the code in the example below is enclosed in a try/catch statement. Instantiating new Reader objects, as well as invoking methods to read and write data, all may result in an exceptional situation. For example, the file you attempt to open may not be found, or the file you attempt to read from may be empty. In these cases, an exception is thrown. |