How to Handle Java Files with Streams
See Java: Tips and Tricks for similar articles.
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 FileWriterandFileReader, 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. ThePrintWriterconstructor is placed in a "try with resources" statement. Therefore the file will be closed regardless of whether an exception occurs or not. TheIOExceptionis possible during execution of theFileWriterconstructor. The program writes two records to the file. TheBufferedReaderconstructor is placed in a "try with resources" statement. Therefore the file will be closed regardless of whether an exception occurs or not. TheFileNotFoundExceptionis possible during execution of theFileReaderconstructor. - Save your file as
HandleJavaFilesWithStreams.java. - 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.

