← Java from Scratch Lesson 56 of 88 · 10 XP

Creating files

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

File f = new File("log.txt");
try {
    if (f.createNewFile())               // true — created, false — it already existed
        System.out.println("created");
    else
        System.out.println("already exists");
} catch (IOException e) {                // no permissions, no folder… — a checked exception
    System.out.println("error: " + e.getMessage());
}

createNewFile() creates an empty file, and does it atomically: if two processes try at the same time, only one creates it. If the parent folder doesn't exist, you get an IOException (call getParentFile().mkdirs() first).

With Files: Files.createFile(path) throws a FileAlreadyExistsException if the file exists.

Task. For each name from the input, create the file and print <name>: created or <name>: already exists. If the name contains a folder (a/b.txt), create the folders too. At the end, print how many files were created.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.