File Input and Output



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 and write files. All of them involve chaining together multiple objects from Java’s standard library in what can only be described as a slightly maddening and confusing manner. 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(FileNotFoundException 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 thetry-catch` block is confusing, check out the notes on exceptions.

Even though the Scanner supports all sorts of specialty methods such as nextInt() and nextDouble(), you probably shouldn’t use them. They don’t handle multi-line files properly, and will ultimately cause you headaches and pain. Instead, just read the file line by line and parse each line individually.

Always make sure to close the file when you are done with it, as we do here using inp.close().

By convention, you should always close a file when you are done with it.

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 that System.out is. That means you can use it just like you do System.out, but the output will go to a file instead of to the screen.

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 (FileNotFoundException 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.

Again, always make sure to close the file when you are done with it, as we do here.