CS 1054: Lab 6

Lab meeting 7: Using files in Java

The purpose of this lab is to introduce you to file input and output. The classes we will use in this lab include BufferedReader, File, FileInputStream, FileOutputStream, PrintStream, and InputStreamReader.

Reading from files

  1. The BufferedReader class, in conjunction with the FileInputStream, File and InputStreamReader classes can be used for reading for files.
  2. Start the BlueJ environment by clickingonStart->Programs->BlueJ.
  3. Open a new project in BlueJ. Name the project FileTest.
  4. Create a new class by clicking on "New Class" on the left. Name the class FileReaderWriterTest.
  5. Declare a field variable in your class of type String called inputFileName.
  6. Also declare the following two variables of the corresponding types shown below. FileInputStream fis; BufferedReader br;
  7. Initialize it to the string input1.txt in the constructor method of your class.
  8. Declare and create new File and FileInputStream objects associated with the input file. Sample code illustrating the use of these classes is shown below. fis = new FileInputStream(new File(inputFileName));
  9. The FileInputStream does not provide a lot of useful methods to access its contents. An easier and more high-level way of accessing data from the file is to associate a BufferedReader class with the FileInputStream. One way of doing it is br = new BufferedReader(new InputStreamReader(fis));
  10. This associates a new BufferedReader with the FileInputStream that we created earlier and allows us to use all the methods of BufferedReader to read from the file.
  11. Create both these objects in the constructor method.
  12. Create a new method called readOneLine() with return type String that reads in one line from the BufferedReader using the readLine() method and prints it to the screen. Refer to the API documentation to get more information about the methods for BufferedReader.
  13. If you try to compile your code, you'll get an error that looks something like this:
    FileReaderTest.java:23: unreported exception java.io.FileNotFoundException; must be caught
     or declared to be thrown
                    fis = new FileInputStream(new File(inputFileName));					
  14. That message indicates that errors might occur when dealing with input/output and these errors might cause disruption it the normal flow of execution of your program. These types of errors are referred to as Exceptions in Java and need to be thrown/caught. We will talk about Exceptions in detail later in the semester.
  15. To compile your program, you need to explicitly throw an Exception. For each method that utilizes the objects created above, we need to throw an exception. For example, the signature of the constructor method will look something like this:
    	public FileReaderWriterTest() throws Exception					
    					
  16. The throws Exception clause has to be inserted after each method in your class.
  17. Download the input1.txt file in your directory.
  18. Invoke the readOneLine() method repeatedly after compiling your code and you can see that each invokation returns one line from the input file. After all the lines are done in the input file, the method starts returning "null".
  19. Create another method called readAllLines() that utilizes the readOneLine() method in a while loop to read all the lines from the input file and prints them to the screen. The condition in the while loop should compare each line to "null". Use this model for the while loop.
            String line;
            line  = readOneLine();
            while(line != null) {
                System.out.println(line);
                line = readOneLine();
            }
    					
  20. Show your work to the GTA.

Writing to Files

  1. We will use the FileOutputStream and PrintStream classes to write to files.
  2. Insert a few more field variables in the same class. Declare a String variable called outputFileName. Initialize it in the constructor to output1.txt. Also declare the following two variables of the corresponding types shown below. FileOutputStream fos; PrintStream ps;
  3. Create objects from these classes in the constructor method like this
            fos = new FileOutputStream(new File(outputFileName));
            ps = new PrintStream(fos);
    					
  4. Write one more method called writeLinesToFile() of type void that utilizes the readOneLine() method indicated above to read all lines from the input file and write them to the output file. Sample code that does this is illustrated below
             String line;
             
             line = readOneLine();
             while(line != null) {
                 ps.println(line);
                 line = readOneLine();
             }
    				
    Note that we are using the println() method of the PrintStream class to print out the line to the output file.
  5. After creating an object of this class and invoking the writeLinesToFile() method, the contents of the input1.txt and output1.txt files should be identical.
  6. Show your work to the GTA.

© Mir Farooq Ali 2003.