Skip to Main Content
Java Cookbook
book

Java Cookbook

by Ian F. Darwin
June 2001
Intermediate to advanced content levelIntermediate to advanced
888 pages
21h 1m
English
O'Reilly Media, Inc.
Content preview from Java Cookbook

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(  );
        }
    }
}
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Cloud-Native Java Development with MicroProfile

Practical Cloud-Native Java Development with MicroProfile

Emily Jiang, Andrew McCright, John Alcorn, David Chan, Alasdair Nottingham
Distributed Computing in Java 9

Distributed Computing in Java 9

Raja Malleswara Rao Malleswara Rao Pattamsetti

Publisher Resources

ISBN: 0596001703Supplemental ContentCatalog PageErrata