Java Files createFile() Method

Beginner
6 min read
Updated: Nov 2026
3 examples
Java 7+

Definition

In Java, Files.createFile(path) creates a new, empty file at path and returns that same path. If a file, folder, or link with that name already exists, it throws FileAlreadyExistsException and leaves the existing entry alone.

The check "does it exist?" and the creation happen as one atomic step, so two programs racing to create the same file cannot both succeed. That makes it useful for lock or marker files. The parent folder must already exist.

A static method of the final utility class java.nio.file.Files, available since Java 7. Call it on the class name, as in Files.createFile(...), after import java.nio.file.Files;. You never create a Files object.

Syntax

Pass the path to create; optional file attributes (such as POSIX permissions) can follow:

Java
Path file = dir.resolve("notes.txt");
Files.createFile(file);                       // new empty file, size 0
Files.createFile(file);                       // throws FileAlreadyExistsException
CallWhat it does
Files.createFile(p)Creates an empty file; fails if p exists.
Files.createFile(p, attr)Also sets attributes atomically, e.g. POSIX permissions.
Files.write(p, bytes)Creates or overwrites a file and fills it in one call.
Files.createDirectories(p.getParent())Run first when the parent folder may be missing.

Since Java 7. Unlike java.io.File.createNewFile(), which returns false when the file exists, Files.createFile tells you why it failed through the exception type.

Library declarations
Java
public static Path createFile(Path path, FileAttribute<?>... attrs) throws IOException

Parameters

ParameterDescription
pathThe file to create. Its parent directory must exist.
attrsOptional FileAttribute values set atomically while creating, such as PosixFilePermissions.asFileAttribute(...). Usually omitted.

Return Value

Return ValueDescription
PathThe path argument itself, now naming an empty file of size 0.

Compare with Similar Methods

Other ways to bring a file into existence:

MethodHow it differs
createTempFile()Picks a unique random name for you, so it never collides.
createDirectory()The same idea for a single folder.
write()Creates or overwrites, and writes content at the same time.

Java Examples

Example 1 — Create an Empty File and Check It

Create notes.txt inside a temp folder, then confirm it exists and is 0 bytes long.

Java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class CreateFileBasic {
    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("demo");
        Path file = dir.resolve("notes.txt");
        System.out.println("Exists before: " + Files.exists(file));
        Path created = Files.createFile(file);
        System.out.println("Created: " + created.getFileName());
        System.out.println("Exists after: " + Files.exists(file));
        System.out.println("Size: " + Files.size(file) + " bytes");
        System.out.println("Returned the same path: " + created.equals(file));
        Files.delete(file);
        Files.delete(dir);
    }
}

How It Works

  1. Only a name so far. dir.resolve("notes.txt") builds the path, but nothing is on disk yet, so the first exists check is false.
  2. One call creates it. createFile makes a zero-length file and hands back the path you passed in, which is why created.equals(file) is true.
  3. Empty means 0 bytes. Files.size reports 0 because nothing has been written into the new file.
  4. Leave no trace. The file is deleted before its folder, since a folder must be empty to be deleted.

Example 2 — Calling createFile Twice Never Overwrites

Write some text, then call createFile on the same path. The call fails, and the text is still there.

Java
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;

public class CreateFileNoOverwrite {
    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("demo");
        Path log = dir.resolve("log.txt");
        Files.createFile(log);
        Files.write(log, "keep me".getBytes(StandardCharsets.UTF_8));
        try {
            Files.createFile(log);
            System.out.println("Created again?");
        } catch (FileAlreadyExistsException e) {
            System.out.println("Second call: " + e.getClass().getSimpleName());
        }
        String text = new String(Files.readAllBytes(log), StandardCharsets.UTF_8);
        System.out.println("Content still: " + text);
        Files.delete(log);
        Files.delete(dir);
    }
}

How It Works

  1. Fill the new file. After the first createFile, Files.write stores the 7 bytes of "keep me".
  2. The name is taken. The second createFile sees the existing file and throws FileAlreadyExistsException, so the "Created again?" line is never printed.
  3. Nothing was truncated. Reading the bytes back still gives "keep me", proving createFile refuses rather than replaces. This is the safe choice for marker or lock files.

Example 3 — Create the Parent Folders First

A file inside a folder that does not exist cannot be created. Catch the error, create the folders with createDirectories, and try again.

Java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;

public class CreateFileParents {
    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("demo");
        Path file = dir.resolve("logs").resolve("app.log");
        try {
            Files.createFile(file);
        } catch (NoSuchFileException e) {
            System.out.println("First try: the logs folder is missing");
        }
        Files.createDirectories(file.getParent());
        Files.createFile(file);
        String rel = dir.relativize(file).toString().replace('\\', '/');
        System.out.println("Second try created: " + rel);
        System.out.println("Is a regular file: " + Files.isRegularFile(file));
        Files.delete(file);
        Files.delete(file.getParent());
        Files.delete(dir);
    }
}

How It Works

  1. Two levels deep. The target is logs/app.log inside the temp folder, but no logs folder exists yet.
  2. No automatic parents. createFile only creates the last name, so it throws NoSuchFileException on Windows, macOS, and Linux alike.
  3. Fix and retry. createDirectories(file.getParent()) creates logs, and the second createFile succeeds.
  4. Portable printing. relativize drops the random temp part and replace('\\', '/') turns Windows separators into slashes, so every system prints logs/app.log.

Frequently Asked Questions

It throws FileAlreadyExistsException and does not touch the existing file. It never overwrites or truncates.
No. If the parent folder does not exist the call fails, typically with NoSuchFileException. Call Files.createDirectories(path.getParent()) first.
Both create an empty file atomically. File.createNewFile returns false when the file exists, while Files.createFile throws FileAlreadyExistsException and returns the Path.
Yes. Checking that the file does not exist and creating it are a single atomic operation with respect to other file-system activity, so only one of several competing programs can succeed.
On Linux and macOS pass PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-------")) as the second argument. On Windows that attribute is not supported and the call throws UnsupportedOperationException.

Next: Files.createLink()

Create a hard link: a second name for the same file data on the same drive.

createLink() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

10 people found this page helpful