How to Handle Java Files with Streams
Streams permit the Java developer to handle files. In other words, a file can be read or created by the use of streams. To read a file, a file input stream reader can be combined with a buffered reader. A record from the file can then be presented to an application. To create a file, a file output writer can be combined with a print writer object to write a stream of data to a file. To learn how to handle Java files with streams, follow these four steps.
- Open your text editor and type in the following Java statements:
The program will create a file and then read the file, displaying the records in the process. When you code the constructor argument of
FileReader, replace the string containing the path (
"c:/JavaStuff") with a directory that exists on your computer. You can retain the file name (
TestFile.txt) or rename it if you prefer. The
PrintWriterconstructor is placed in a "try with resources" statement. Therefore the file will be closed regardless of whether an exception occurs or not. The
IOExceptionis possible during execution of the
FileWriterconstructor. The program writes two records to the file. The
BufferedReaderconstructor is placed in a "try with resources" statement. Therefore the file will be closed regardless of whether an exception occurs or not. The
FileNotFoundExceptionis possible during execution of the
- Save your file as
- Open a command prompt and navigate to the directory containing your Java program. Then type in the command to compile the source and hit Enter.
- Type in the command to run your program and hit Enter. The output displays the two records that were written to the file.