00:00

How to Create a File in Java: 5 Ways with Examples

Last updated:

Applications constantly create files: invoices, exports, upload buffers and log files. The important question is usually not how to create a file but what should happen if it already exists. Java's different methods answer that question differently.

This tutorial shows every common way to create a file in Java 25, each with a complete, tested example.

1. What Is Creating a File in Java?

Creating a file means adding a new, usually empty, entry to a folder in the file system. The folder must exist, and creation can fail if the file is already there, if you lack permission or if the disk is full. Remember that new File("x") and Path.of("x") only create Java objects, not files.

2. Ways to Create a File at a Glance

WayIf the file existsSince
Files.createFile(path)Throws FileAlreadyExistsExceptionJava 7
file.createNewFile()Returns falseJava 1.2
Files.createDirectories() + createFile()Throws for the file; existing folders are fineJava 7
Files.createTempFile()Never: the name is always uniqueJava 7
Files.writeString(..., CREATE_NEW)Throws FileAlreadyExistsExceptionJava 11

3. Using Files.createFile()

A billing system creates one file per invoice and must never overwrite an existing one.

CreateWithFilesCreateFile.java
import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;

public class CreateWithFilesCreateFile {
    public static void main(String[] args) throws IOException {
        Path folder = Files.createTempDirectory("invoices");
        Path invoice = folder.resolve("INV-001.txt");

        Files.createFile(invoice);                                   // fails if it already exists
        System.out.println("Created: " + invoice.getFileName() + ", size " + Files.size(invoice));
        try {
            Files.createFile(invoice);
        } catch (FileAlreadyExistsException e) {
            System.out.println("Second attempt: FileAlreadyExistsException");
        }
        Files.delete(invoice);
        Files.delete(folder);
    }
}
Output
Created: INV-001.txt, size 0
Second attempt: FileAlreadyExistsException

How it works

  1. Files.createFile() creates an empty file.
  2. A second attempt throws FileAlreadyExistsException, so no data can be overwritten by accident.

4. Using File.createNewFile()

The classic java.io method reports the outcome as a boolean.

CreateWithCreateNewFile.java
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

public class CreateWithCreateNewFile {
    public static void main(String[] args) throws IOException {
        File folder = Files.createTempDirectory("tickets").toFile();
        File ticket = new File(folder, "ticket-42.txt");

        System.out.println("First call:  " + ticket.createNewFile());   // true: created
        System.out.println("Second call: " + ticket.createNewFile());   // false: already there
        ticket.delete();
        folder.delete();
    }
}
Output
First call:  true
Second call: false

How it works

  1. createNewFile() returns true when it created the file.
  2. It returns false when the file already exists, so it is a safe "create if missing".

5. Creating a File Inside New Folders

A photo app stores captions in a year and album folder structure that may not exist yet.

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

public class CreateWithParents {
    public static void main(String[] args) throws IOException {
        Path root = Files.createTempDirectory("photos");
        Path album = root.resolve("2026").resolve("goa-trip");
        Path caption = album.resolve("captions.txt");

        Files.createDirectories(album);                 // creates 2026 and goa-trip
        Files.createFile(caption);
        System.out.println("Exists: " + Files.exists(caption));
        System.out.println("Relative path: " + root.relativize(caption));

        Files.delete(caption);
        Files.delete(album);
        Files.delete(album.getParent());
        Files.delete(root);
    }
}
Output
Exists: true
Relative path: 2026/goa-trip/captions.txt

How it works

  1. Files.createDirectories() creates every missing folder and does nothing for folders that already exist.
  2. Files.createFile() then creates the file inside the new folders.

6. Creating a Temporary File

An upload service needs a scratch file with a name that cannot clash with others.

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

public class CreateTempFile {
    public static void main(String[] args) throws IOException {
        Path upload = Files.createTempFile("upload-", ".tmp");     // unique name in the temp folder
        String name = upload.getFileName().toString();

        System.out.println("Starts with prefix: " + name.startsWith("upload-"));
        System.out.println("Ends with suffix:   " + name.endsWith(".tmp"));
        System.out.println("Empty: " + (Files.size(upload) == 0));
        Files.delete(upload);
    }
}
Output
Starts with prefix: true
Ends with suffix:   true
Empty: true

How it works

  1. Files.createTempFile() creates an empty file with a unique name in the system temporary folder.
  2. The prefix and suffix you pass become part of the name.
  3. Delete temporary files when you no longer need them.

7. Creating and Writing in One Step

When you want to create a file and write to it at once, but never overwrite, use CREATE_NEW.

CreateWhileWriting.java
import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;

public class CreateWhileWriting {
    public static void main(String[] args) throws IOException {
        Path folder = Files.createTempDirectory("contracts");
        Path contract = folder.resolve("draft.txt");

        // CREATE_NEW: create and write in one step, but never overwrite
        Files.writeString(contract, "Draft v1\n", StandardOpenOption.CREATE_NEW);
        System.out.print("Written: " + Files.readString(contract));
        try {
            Files.writeString(contract, "Draft v2\n", StandardOpenOption.CREATE_NEW);
        } catch (FileAlreadyExistsException e) {
            System.out.println("Overwrite blocked: FileAlreadyExistsException");
        }
        Files.delete(contract);
        Files.delete(folder);
    }
}
Output
Written: Draft v1
Overwrite blocked: FileAlreadyExistsException

How it works

  1. StandardOpenOption.CREATE_NEW creates the file and fails if it already exists.
  2. The existence check and the creation happen as one step, so two programs cannot both create it.

8. Common Mistakes and Best Practices

  • Thinking new File() creates a file. Call a creation method.
  • Forgetting the parent folders. Use Files.createDirectories() first.
  • Checking exists() and then creating. Another program can create the file in between; use createFile() or CREATE_NEW and handle the exception.
  • Ignoring the result of createNewFile(). Check whether it returned true.
  • Leaving temporary files behind. Delete them when done.

9. Summary

  • Files.createFile() creates an empty file and throws if it already exists.
  • File.createNewFile() returns true or false instead.
  • Create missing folders first with Files.createDirectories().
  • Files.createTempFile() always produces a unique name.
  • CREATE_NEW creates and writes in one safe step.

Related Tutorials

10. Official Java Documentation References