How to Create a File in Java

Naveen AnamaneniUpdated · 3 min read
easyJava 25javafilesnio

Creating a file in Java means making a new, empty file on disk at a given path. The modern way is Files.createFile(path) from NIO.2, which throws an exception if the file already exists or its folder is missing. The older File.createNewFile() returns false instead. Java can also create temporary files with unique names. In this lesson, you will learn each way and how to handle the usual problems.

Ways to Create a File

MethodDescription
Files.createFile(path)It is used to create a new empty file; throws FileAlreadyExistsException if it exists.
Files.createDirectories(dir)It creates any missing parent folders first.
Files.createTempFile(prefix, suffix)It creates a file with a unique name in the system's temporary folder.
Files.writeString(path, text)It creates the file (or overwrites it) and writes text in one step.
new File(name).createNewFile()It creates the file and returns true, or false if it already exists (legacy).

Example: Creating Files Safely

Let's see an example that creates a file, tries again, and handles a missing folder.

CreateFiles.java▶ Try it
import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
 
public class CreateFiles {
    public static void main(String[] args) throws IOException {
        Path file = Path.of("attendance.txt");
        Files.createFile(file);
        System.out.println("Created: " + Files.exists(file)
            + ", size " + Files.size(file));
 
        try {
            Files.createFile(file);
        } catch (FileAlreadyExistsException e) {
            System.out.println("Already exists: " + e.getMessage());
        }
 
        Path nested = Path.of("reports", "2026", "navika.txt");
        try {
            Files.createFile(nested);
        } catch (NoSuchFileException e) {
            System.out.println("Missing folder for: " + e.getMessage());
        }
 
        Files.createDirectories(nested.getParent());
        Files.createFile(nested);
        System.out.println("Created after making folders: "
            + Files.exists(nested));
    }
}
Output
Created: true, size 0
Already exists: attendance.txt
Missing folder for: reports/2026/navika.txt
Created after making folders: true

Explanation: The first createFile makes an empty file. The second fails with FileAlreadyExistsException, so an existing file is never overwritten by accident. Creating a file inside folders that don't exist fails with NoSuchFileException; createDirectories makes the missing folders, after which the file can be created.

Example: Temporary Files

TempFiles.java▶ Try it
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
 
public class TempFiles {
    public static void main(String[] args) throws IOException {
        Path temp = Files.createTempFile("upload-", ".csv");
        String name = temp.getFileName().toString();
        System.out.println("Starts with upload-? "
            + name.startsWith("upload-"));
        System.out.println("Ends with .csv? " + name.endsWith(".csv"));
        Files.writeString(temp, "Advitha,85");
        System.out.println("Content: " + Files.readString(temp));
        Files.delete(temp);
        System.out.println("Deleted: " + Files.notExists(temp));
    }
}
Output
Starts with upload-? true
Ends with .csv? true
Content: Advitha,85
Deleted: true

Explanation: createTempFile adds a random number between the prefix and suffix, so two programs never get the same name. Temporary files aren't deleted automatically; delete them when you're done.

Common Mistakes

Calling createFile when the folder doesn't exist. Call createDirectories(path.getParent()) first.

Ignoring the false from File.createNewFile(). The file already existed and nothing was created.

Leaving temporary files behind. Delete them, or use deleteOnExit on a File for short programs.

Practice

  1. Easy: Create the files day1.txt to day5.txt in a folder diary.
  2. Harder: Write a method createUnique(Path dir, String base) that creates base.txt, or base-1.txt, base-2.txt and so on if earlier names exist.

Quick check: Creating files

4 questions
1What does Files.createFile do if the file exists?
2What happens if the parent folder is missing?
3Which method creates missing parent folders?
4Are temporary files deleted automatically?

Key Takeaways

Was this tutorial helpful?

Lesson 356 of 482