O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Creating a File

Problem

You need to create a new file on disk, but you don’t want to write into it.

Solution

Use a java.io.Fileobject’s createNewFile( ) method.

Discussion

You could easily create a new file by constructing a FileOutputStream or FileWriter (see Section 9.4). But then you’d have to remember to close it as well. Sometimes you want a file to exist, but you don’t want to bother putting anything into it. This might be used, for example, as a simple form of interprogram communication: one program could test for the presence of a file, and interpret that to mean that the other program has reached a certain state. Here is code that simply creates an empty file for each name you give:

import java.io.*;

/**
 * Create one or more files by name.
 * The final "e" is omitted in homage to the underlying UNIX system call.
 */
public class Creat {
    public static void main(String[] argv) throws IOException {

        // Ensure that a filename (or something) was given in argv[0]
        if (argv.length == 0) {
            System.err.println("Usage: Creat filename");
            System.exit(1);
        }

        for (int i = 0; i< argv.length; i++) {
            // Constructing a File object doesn't affect the disk, but
            // the createNewFile(  ) method does.
            new File(argv[i]).createNewFile(  );
        }
    }
}

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required