ONJava.com -- The Independent Source for Enterprise Java
oreilly.comSafari Books Online.Conferences.

advertisement

AddThis Social Bookmark Button
   Print.Print
Email.Email article link
The Java Cookbook (cover)

Java Recipe of the Day

The following recipe is from The Java Cookbook, by Ian Darwin. All links in this recipe point to the online version of the book on the Safari Bookshelf.

Buy it now, or read it online on the Safari Bookshelf.


11.2. Creating a File

. Discussion

You could easily create a new file by constructing a FileOutputStream or FileWriter (see Recipe 10.6). 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( );
        }
    }
}

View the past week's recipes: Today | Yesterday | 3 days ago | 4 days ago | 5 days ago | 6 days ago | A week ago