CMUQ 15-121 File I/O



1. Introduction

Reading and writing from files is an important part of any programming language. Java, for better or for worse, has many different ways to read from files. All of them involve chaining together multiple objects from Java’s standard library in what can only be described as slightly maddening and confusing. In this course, we’ll only discuss a few of the possible ways.

2. File Reading

Do you remember the Scanner class we used to get input from a user? You can also use it to read data from a file. Consider the following program that reads and prints all the lines from the file GirlName.txt.

import java.io.FileReader;
import java.util.Scanner;

public class FileReadingDemo {
    
    public static void main(String args[]) {
        FileReader fr;
        
        try {
            fr = new FileReader("GirlName.txt");
            
        } catch(Exception e) {
            System.out.println("Could not open the file!");
            return;
        }
        Scanner inp = new Scanner(fr);
        
        // Read and print out all lines
        while (inp.hasNextLine()) {
            String theLine = inp.nextLine();
            System.out.println(theLine);
        }
        inp.close();
    }

}

As you can see, we create a new FileReader and give it the name of the file we want to open. We then pass that to the constructor for a new Scanner. Now that we have a Scanner we can use it in the same way that we used it for user input. The difference is that in this case the Scanner is reading from a file instead of the user. (If the try-catch block is confusing, checkout the notes on exceptions.)

Always make sure to close the file when you are done with it, as we do here on line 23.

3. File Writing

When writing a file, we have the option of opening the file as a PrintWriter, which is the same type of object System.out is. Consider this example:

import java.io.PrintWriter;

public class FileWritingDemo {

    public static void main(String[] args) {
        PrintWriter out;
        
        try {
            out = new PrintWriter("outfile.txt");
        }
        catch (Exception e) {
            System.out.println("Error: Could not open the file");
            return;
        }
        
        out.println("Hi there, this is a line");
        out.println("This works just like System.out.println");
        for(int i = 0; i < 10; i++) {
            out.print(i + " ");
        }
        out.close();
    }

}

As you can see, the PrintWriter can do everything that you already do with System.out. The difference is that instead of printing to the screen, the data is written to a file.

Always make sure to close the file when you are done with it, as we do here on line 21.

4. Helper Functions

Rather than writing the same code every time you want to open a file for reading or writing, consider using these helper functions. You can paste them into any of your classes and just use them as is. We’ll make use of them in the demo code we write in class. You can also make use of them in the homework.

    /*
     * Helper method to open files for reading.
     * It returns a Scanner object that you can use.
     * Be sure to call .close() on that object when you are done.
     */
    public static Scanner getFileScanner(String filename)
    {
        Scanner myFile;
        try { 
            myFile = new Scanner(new FileReader(filename)); 
        } catch (Exception e) {
            System.out.println("File not found: " + filename);
            return null;
        }
        return myFile;
    }

    /*
     * Helper method to open files for writing.
     * It returns a PrintWriter that you can use.
     * Be sure to call .close() on that object when you are done.
     */
    public static PrintWriter getFileWriter(String filename)
    {
        PrintWriter outFile;
        try { 
            outFile = new PrintWriter(filename);
        }
        catch (Exception e)
        {
            System.out.println("Error opening file: " + filename);
            return null;
        }
        return outFile;
    }