Java File.mkdir and createNewFile
Create one directory, a missing directory chain, or a new empty file.
A simple example
File.mkdir and createNewFile
- Start with Empty directory
- Do this Create a.txt once
- Result New file exists
Syntax
public boolean createNewFile() throws IOException
JDK 21 declarations (3)
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaReserve the first receipt in a new branch
A retailer opens a new branch and needs folders for its first trading day. Create the branch, create the nested daily folder, and reserve a receipt name that another clerk might also request.
import java.nio.file.*;
import java.io.*;
class Main {
public static void main(String[] args) throws Exception {
Path desk = Files.createTempDirectory("file-lesson-");
try {
File branch = new File(desk.toFile(), "branch");
System.out.println(branch.mkdir());
File daily = new File(branch, "orders/day1");
System.out.println(daily.mkdirs());
File receipt = new File(daily, "001.txt");
System.out.println(receipt.createNewFile());
System.out.println(receipt.createNewFile());
} finally {
try (var paths = Files.walk(desk)) {
for (Path p : paths.sorted(java.util.Comparator.reverseOrder()).toList())
Files.deleteIfExists(p);
}
}
}
}
true true true false
The first reservation creates the name. The second reports that it is already taken.
Notice a missing parent
A lecturer tries to create a week folder before its course folder has been set up. Compare the single-directory operation with the operation that can also create the missing parent.
import java.nio.file.*;
import java.io.*;
class Main {
public static void main(String[] args) throws Exception {
Path desk = Files.createTempDirectory("file-lesson-");
try {
File week = new File(desk.toFile(), "course/week1");
System.out.println(week.mkdir());
System.out.println(week.mkdirs());
} finally {
try (var paths = Files.walk(desk)) {
for (Path p : paths.sorted(java.util.Comparator.reverseOrder()).toList())
Files.deleteIfExists(p);
}
}
}
}
false true
The first attempt cannot create the missing course directory. The second creates both directories.
Prepare a gallery label
A curator stores a short UTF-8 caption beside an exhibit. Two desks try to reserve the same filename using exclusive creation. What happens to the first successful reservation when the second desk tries?
What to watch for
A false return from mkdir or mkdirs can mean the directory already exists. createNewFile atomically checks and creates the final file.