Java Create Files

Su Suriya Ravichandran Updated 18 Nov 2026
9 min read ·Lesson 135 of 306

Ways to Create a File

Java offers several ways to create a file. They differ in one important way: what happens if the file already exists.

MethodIf the file already existsPackage
Files.createFile(path)Throws FileAlreadyExistsExceptionjava.nio.file
File.createNewFile()Returns falsejava.io
Files.writeString(path, text) / Files.write(...)Replaces its content (by default)java.nio.file
Files.writeString(path, text, CREATE_NEW, WRITE)Throws FileAlreadyExistsExceptionjava.nio.file
Files.createTempFile(prefix, suffix)Can't happen — it generates a new, unique namejava.nio.file

Choosing the right one matters. Some code must never overwrite existing data (receipts, uploaded files, audit logs), while other code should simply produce a fresh output each time (a daily report). Creating an empty file explicitly is also useful as a marker or lock — for example a .done file that tells another process an export is complete.

Files.createFile

import java.io.IOException;
import java.nio.file.*;

public class Create1 {
    public static void main(String[] args) throws IOException {
        Path file = Path.of("orders.log");
        Path created = Files.createFile(file);
        System.out.println("created " + created + ", size " + Files.size(created));

        try {
            Files.createFile(file);
        } catch (FileAlreadyExistsException e) {
            System.out.println("FileAlreadyExistsException: " + e.getFile());
        }

        try {
            Files.createFile(Path.of("archive/2026/orders.log"));
        } catch (NoSuchFileException e) {
            System.out.println("NoSuchFileException: " + e.getFile());
        }
    }
}

Output (when run in an empty folder):

created orders.log, size 0
FileAlreadyExistsException: orders.log
NoSuchFileException: archive/2026/orders.log

How it works:

  1. Files.createFile(path) creates a new, empty file (size 0) and returns its Path.
  2. The check and the creation are one atomic operation. The operating system checks whether the name is free and creates the file in a single step, so no other program can create a file with the same name in between. That's why a second call fails with FileAlreadyExistsException instead of silently succeeding or overwriting.
  3. Parent folders are not created. archive/2026 doesn't exist, so the call throws NoSuchFileException. Its getFile() reports the path that was being created.
  4. getFile() on these exceptions (both extend FileSystemException) returns the affected path as a String, which is handy for error messages.

File.createNewFile (java.io)

The older java.io.File API has an equivalent that reports the result as a boolean:

import java.io.*;

public class Create2 {
    public static void main(String[] args) throws IOException {
        File file = new File("invoice.txt");
        System.out.println("first call:  " + file.createNewFile());
        System.out.println("second call: " + file.createNewFile());
        try {
            new File("no/such/dir/invoice.txt").createNewFile();
        } catch (IOException e) {
            System.out.println("IOException: " + e.getMessage());
        }
    }
}

Output (on Linux):

first call:  true
second call: false
IOException: No such file or directory
  • true means the file was created; false means a file with that name already existed. It is also atomic.
  • A missing parent folder throws IOException with the operating system's message, which is less specific than NoSuchFileException and differs between operating systems (Windows reports "The system cannot find the path specified").

Ignoring the boolean is a common oversight: file.createNewFile(); on its own line silently does nothing when the file exists. You'll see this method in older code; for new code, Files.createFile gives clearer exceptions.

Creating the Parent Folders First

Files usually go into a folder structure that may not exist yet — for example one folder per year and month.

import java.io.IOException;
import java.nio.file.*;

public class Create3 {
    public static void main(String[] args) throws IOException {
        Path file = Path.of("archive", "2026", "11", "orders.log");
        Files.createDirectories(file.getParent());
        Files.createFile(file);
        System.out.println("created " + file);
        System.out.println("again: " + Files.createDirectories(file.getParent()));

        try {
            Files.createDirectory(Path.of("archive"));
        } catch (FileAlreadyExistsException e) {
            System.out.println("createDirectory: already exists " + e.getFile());
        }
    }
}

Output (on Linux; Windows prints 0 instead of /`):

created archive/2026/11/orders.log
again: archive/2026/11
createDirectory: already exists archive
  • Path.of("archive", "2026", "11", "orders.log") joins the parts with the platform's separator, so the code works on every operating system without hard-coding / or ``.
  • file.getParent() returns the folder part, archive/2026/11.
  • Files.createDirectories(dir) creates every missing folder along the path, and does nothing if they already exist — the second call succeeds and simply returns the path. This makes it safe to call every time before writing a file.
  • Files.createDirectory(dir) (singular) creates exactly one folder and fails if it already exists or if its parent is missing. Use it when you need to know that you created the folder — for example, to claim a unique working directory.

Creating a File by Writing to It

Most of the time you don't need an empty file — you want a file with content. The write methods create the file automatically:

Files.writeString(Path.of("report.txt"), "Total: 5630.75\n");

With no options, this uses CREATE, TRUNCATE_EXISTING and WRITE: create the file if it doesn't exist, otherwise erase its existing content and write the new content. That's right for generated output, but dangerous for data that must never be lost. Pass open options to change the behaviour:

import java.io.IOException;
import java.nio.file.*;
import static java.nio.file.StandardOpenOption.*;

public class Create4 {
    public static void main(String[] args) throws IOException {
        Path receipt = Path.of("receipt-1001.txt");
        Files.writeString(receipt, "Receipt 1001: 2 x Gel pen = 25.00\n", CREATE_NEW, WRITE);
        System.out.print(Files.readString(receipt));
        try {
            Files.writeString(receipt, "Receipt 1001: OVERWRITTEN\n", CREATE_NEW, WRITE);
        } catch (FileAlreadyExistsException e) {
            System.out.println("refused to overwrite " + e.getFile());
        }
        Files.writeString(receipt, "Receipt 1001: replaced\n");
        System.out.print(Files.readString(receipt));
    }
}

Output:

Receipt 1001: 2 x Gel pen = 25.00
refused to overwrite receipt-1001.txt
Receipt 1001: replaced
OptionEffect
CREATECreate the file if it doesn't exist; open it if it does
CREATE_NEWCreate the file; fail with FileAlreadyExistsException if it exists (atomic)
TRUNCATE_EXISTINGIf the file exists, discard its content first
APPENDWrite at the end of the existing content
WRITEOpen for writing

CREATE_NEW combines creation and writing in one call with the same atomic guarantee as Files.createFile. The static import import static java.nio.file.StandardOpenOption.*; lets you write CREATE_NEW instead of StandardOpenOption.CREATE_NEW. The last call, without options, replaces the content — exactly what CREATE_NEW prevented. Writing files is covered fully in the Write Files lesson.

Temporary Files

A temporary file holds data needed only for a short time: a file being downloaded before it's verified, an export being generated before it's emailed, a chunk of a large upload. Java can create one with a name guaranteed to be unique, in the operating system's temporary folder.

import java.io.IOException;
import java.nio.file.*;

public class Temp {
    public static void main(String[] args) throws IOException {
        System.out.println("tmpdir:    " + System.getProperty("java.io.tmpdir"));

        Path tmp = Files.createTempFile("export-", ".csv");
        System.out.println("temp file: " + tmp);

        Path work = Files.createTempDirectory("import-");
        Path chunk = Files.createTempFile(work, "chunk-", ".part");
        System.out.println("temp dir:  " + work);
        System.out.println("in dir:    " + chunk);

        tmp.toFile().deleteOnExit();
    }
}

Output (the random numbers change on every run; Windows uses a folder such as `C:\Users\Asha\AppData\Local\Temp`):

tmpdir:    /tmp
temp file: /tmp/export-18326705088785741869.csv
temp dir:  /tmp/import-2169535330125668042
in dir:    /tmp/import-2169535330125668042/chunk-5222000418523853653.part
  • createTempFile(prefix, suffix) creates an empty file named prefix + random number + suffix in the folder given by the java.io.tmpdir system property. Passing null as the suffix uses .tmp.
  • createTempDirectory(prefix) creates a uniquely named folder, and createTempFile(dir, prefix, suffix) creates a file inside a specific folder — useful for keeping all of a job's temporary files together.
  • Temporary files are not deleted automatically. deleteOnExit() asks the JVM to delete the file when it shuts down normally, but it doesn't run if the process is killed, and each registration stays in memory until exit, so it's unsuitable for long-running servers that create many files. The reliable approach is to delete the file yourself in a finally block or a try-with-resources close() method once you're done (see the TempWorkspace example in the Try With Resources lesson).

On Unix-like systems, temporary files are created with permissions that allow only the owner to read and write them, which matters because the temp folder is shared by all users of the machine.

Setting Permissions at Creation (Linux and macOS)

Files containing secrets (API keys, private keys, tokens) should be readable only by their owner. On POSIX systems you can set permissions as part of creation, so the file is never briefly readable by others:

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.*;
import java.util.Set;

public class Perms {
    public static void main(String[] args) throws IOException {
        Set<PosixFilePermission> ownerOnly = PosixFilePermissions.fromString("rw-------");
        Path secret = Files.createFile(Path.of("api-key.txt"),
                PosixFilePermissions.asFileAttribute(ownerOnly));
        System.out.println(PosixFilePermissions.toString(Files.getPosixFilePermissions(secret)));
    }
}

Output:

rw-------
  • "rw-------" is the familiar Unix notation: read and write for the owner, nothing for the group or others.
  • asFileAttribute turns the permission set into a FileAttribute, which createFile, createDirectory and createTempFile all accept as extra arguments.
  • The process's umask can remove permissions from what you request, but never adds any, so owner-only permissions are kept as requested.
  • On Windows, which doesn't use POSIX permissions, this call throws UnsupportedOperationException. Cross-platform code must check FileSystems.getDefault().supportedFileAttributeViews().contains("posix") first.

Practical Example: Creating a File Without Overwriting

Downloads folders and export tools never overwrite an existing file; they pick the next free name: report.csv, report (1).csv, report (2).csv. The safe way to do this relies on the atomic behaviour of createFile.

import java.io.IOException;
import java.nio.file.*;
import java.time.LocalDate;

public class Unique {
    static Path createUnique(Path dir, String baseName, String extension) throws IOException {
        Files.createDirectories(dir);
        for (int n = 0; n < 1000; n++) {
            String name = n == 0 ? baseName + extension : baseName + " (" + n + ")" + extension;
            try {
                return Files.createFile(dir.resolve(name));
            } catch (FileAlreadyExistsException e) {
                // name taken; try the next number
            }
        }
        throw new IOException("no free file name for " + baseName + " in " + dir);
    }

    public static void main(String[] args) throws IOException {
        Path dir = Path.of("exports");
        String base = "sales-" + LocalDate.of(2026, 11, 15);
        for (int i = 0; i < 3; i++) {
            System.out.println(createUnique(dir, base, ".csv").getFileName());
        }
    }
}

Output (first run in an empty folder):

sales-2026-11-15.csv
sales-2026-11-15 (1).csv
sales-2026-11-15 (2).csv

Why it is written this way:

  1. It tries to create, rather than checking first. A version using if (!Files.exists(path)) Files.createFile(path) has a race condition: if two threads or two server instances run at the same moment, both can see that the name is free, and one of them fails or overwrites the other's file. Because createFile checks and creates in one atomic step, exactly one caller gets each name, and the others move on to the next number.
  2. The empty catch is deliberate. FileAlreadyExistsException is the expected signal "this name is taken", and the comment explains why it's ignored. Any other IOException (no permission, disk full) is not caught and propagates to the caller.
  3. The loop has a limit. Without one, a bug or a folder full of files would cause an endless loop; after 1,000 attempts, the method fails with a clear message.
  4. The method returns the created Path, so the caller knows which name was chosen and can write the content into it.

When human-readable names don't matter, a random name such as UUID.randomUUID() + ".csv" avoids collisions without a loop, which is the usual approach for storing uploaded files on a server. Never use the name a user supplies directly as a file name: values like ../../etc/passwd would let a user write outside the intended folder. The File Paths lesson shows how to validate such paths.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Create Files and get answers drawn from it.

Signed-in readers only.