Introduction to Programming (CPSC 124)
—Hobart & William Smith Colleges, Fall 2014
Working With Files in Java
Home | Syllabus | Calendar | Class Notes | Labs and Projects | General Notes

Essential Techniques

Necessary imports

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;

You can also use the "wildcard" for the java.io classes, which imports the entire java.io namespace:

import java.util.Scanner;
import java.io.*;

Constructor syntax:

new File( name of file )

For example, we can create a representation of the file nums.data and store this in the variable numF:

File numF = new File("nums.data")

NOTES:


The key thing to remember about File objects is that they represent paths in a file system—essentially, entries in the record of files on some hard disk or other volume—rather than actual files. In fact, File objects can represent either files or folders, whether they exist already or not!

Some other File methods:


Opening a file for reading:

Scanner inp = new Scanner( File object );

To use our "nums.data" example above:

File numF = new File("nums.data");
Scanner inp = new Scanner(numF);

Once constructed, you can read tokens with inp in the same way that you do for a Scanner constructed for a String or System.in.

NOTES:


Opening a file for writing:

    File fout = new File( File object );
    PrintWriter outp = new PrintWriter( fout );

That's really it. Once you construct outp, you use it almost exactly the same way you use System.out, using calls to print(), println(), printf(), and so on. See

http://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html

for a complete description of this interface.

NOTES:

Politeness requirement: close files when you're done.

This means close them at the point where you are no longer going to use that reader or writer again: at the end of a file, when you replace the Scanner object stored in a variable with a new one, just before a variable reader or writer goes out of scope, etc. Both Scanner and PrintWriter do this in the same way, using a close() method call:

inp.close();
outp.close();

Examples

Here's a quick demo file that you can use to explore file reading. Try it from a folder where the file nums.data exists and one where it doesn't.

import java.io.*;
import java.util.Scanner;

public class FileIODemo {
    public static void main(String[] args)  throws IOException {
        File numsF = new File("nums.data");
        printInfo(numsF);
        
        PrintStream numOut = new PrintStream(moreNums);
        for (int i = 0; i < 20; i ++ ) {
            numOut.println(i);
        }
        
        printInfo(moreNums);

        numOut.close();
        
    } // main
    
    static void printInfo(File f) throws IOException {
        System.out.println(f.getName() + ":");
        System.out.println("full path name: " + f.getAbsolutePath());
        System.out.println("exists: " + f.exists());
        System.out.println("readable: " + f.canRead());
        System.out.println("number of characters: " + f.length());
        
        if (f.exists()) {
            Scanner fReader = new Scanner(f);
            int line = 0;
            
            while(fReader.hasNext()) {
                fReader.nextLine();
                line += 1;
            }
            
            System.out.println("number of lines: " + line);
            
            // Politeness requirement:  
            //     When you're done with a file reader, (or writer), close it.  
            //     This way, the operating system doesn't need to protect  
            //     against concurrent modification unnecessarily
        
            fReader.close();
        }
    } // printInfo
} // FileIODemo

Here's a bells-and-whistles version of last week's Pig Latin project. It works with files, and uses patterns that split up the input in a way that allows us to preserve all punctuation, spacing, and capitalization from the original input: (link)

Try it out with this file, twelfth_night.txt, which contains the complete text of Shakespeare's wonderful comedy, Twelfth Night.

Some public domain data sites


John H. E. Lasseter