How to Handle Java Files with Streams

  • google plus

In Brief...

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.

Instructions

  1. Open your text editor and type in the following Java statements:
    Java Source for Handle Files
    The program will create a file and then read the file, displaying the records in the process. When you code the constructor argument of FileWriter and 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 PrintWriter constructor is placed in a "try with resources" statement. Therefore the file will be closed regardless of whether an exception occurs or not. The IOException is possible during execution of the FileWriter constructor. The program writes two records to the file. The BufferedReader constructor is placed in a "try with resources" statement. Therefore the file will be closed regardless of whether an exception occurs or not. The FileNotFoundException is possible during execution of the FileReader constructor.
  2. Save your file as HandleJavaFilesWithStreams.java.
  3. 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.
    Compile Source for Handle Files
  4. Type in the command to run your program and hit Enter. The output displays the two records that were written to the file.
    Run Handle Files

Author: Stephen Withrow

Stephen has over 30 years' experience in training, development, and consulting in a variety of technology areas including Java, C, C++, XML, JavaScript, AJAX, Tomcat, JBoss, Oracle, and DB2. His background includes design and implementation of business solutions on client/server, Web, and enterprise platforms. Stephen is a published writer in both technical and non-technical endeavors. Stephen received an undergraduate degree in Computer Science and Physics from Florida State University.

Discuss