Java Cookbook, Second Edition

Problem

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

Solution

Use a java.io.File object's createNewFile( ) method.

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( ); } } }

Категории