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;

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

import java.util.Scanner;

Constructor syntax:

new File( name of file )

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

File numF = new File("")


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 "" example above:

File numF = new File("");
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


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

for a complete description of this interface.


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:



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

import java.util.Scanner;

public class FileIODemo {
    public static void main(String[] args)  throws IOException {
        File numsF = new File("");
        File moreNums = new File("");
        System.out.print("** generating new file ... ");        
        PrintStream numOut = new PrintStream(moreNums);
        for (int i = 0; i < 20; i ++ ) {
            numOut.println((int) (Math.random() * 1000) + 1);
        System.out.println(" done. **");        

    } // 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()) {
                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
    } // printInfo
} // FileIODemo

Some public domain data sites

John H. E. Lasseter