How to Create a File in Java: 5 Ways with Examples
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
| Way | If the file exists | Since |
|---|---|---|
Files.createFile(path) | Throws FileAlreadyExistsException | Java 7 |
file.createNewFile() | Returns false | Java 1.2 |
Files.createDirectories() + createFile() | Throws for the file; existing folders are fine | Java 7 |
Files.createTempFile() | Never: the name is always unique | Java 7 |
Files.writeString(..., CREATE_NEW) | Throws FileAlreadyExistsException | Java 11 |
3. Using Files.createFile()
A billing system creates one file per invoice and must never overwrite an existing one.
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);
}
}
Created: INV-001.txt, size 0 Second attempt: FileAlreadyExistsException
How it works
Files.createFile()creates an empty file.- 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.
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();
}
}
First call: true Second call: false
How it works
createNewFile()returnstruewhen it created the file.- It returns
falsewhen 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.
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);
}
}
Exists: true Relative path: 2026/goa-trip/captions.txt
How it works
Files.createDirectories()creates every missing folder and does nothing for folders that already exist.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.
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);
}
}
Starts with prefix: true Ends with suffix: true Empty: true
How it works
Files.createTempFile()creates an empty file with a unique name in the system temporary folder.- The prefix and suffix you pass become part of the name.
- 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.
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);
}
}
Written: Draft v1 Overwrite blocked: FileAlreadyExistsException
How it works
StandardOpenOption.CREATE_NEWcreates the file and fails if it already exists.- 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; usecreateFile()orCREATE_NEWand handle the exception. - Ignoring the result of
createNewFile(). Check whether it returnedtrue. - Leaving temporary files behind. Delete them when done.
9. Summary
Files.createFile()creates an empty file and throws if it already exists.File.createNewFile()returnstrueorfalseinstead.- Create missing folders first with
Files.createDirectories(). Files.createTempFile()always produces a unique name.CREATE_NEWcreates and writes in one safe step.