Java Create Files
Before you can save data, you often need to create a file. Java lets you create an empty file, create the folders that hold it, and check whether a file already exists so you do not overwrite something by accident.
Creating a file means asking the operating system to make a new, empty entry on disk at a given path. Java gives you a couple of ways to do this. The classic way uses the createNewFile method on a File object, and the modern way uses Files.createFile with a Path. Both can fail, so both involve handling an IOException.
Creating a file with File.createNewFile
import java.io.File;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
File file = new File("greeting.txt");
if (file.createNewFile()) {
System.out.println("File created: " + file.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
}The createNewFile method returns a boolean. It returns true when a brand new file was made, and false when a file with that name was already there. It never overwrites an existing file, which makes it safe to call. It throws an IOException only if the operating system refuses, for example when the folder does not exist.
Creating folders too
A file cannot be created in a folder that does not exist. If you want to place a file inside a new directory, create the directory first. The mkdirs method makes all the missing parent folders in one call.
Creating a folder then a file inside it
import java.io.File;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
File folder = new File("data/reports");
folder.mkdirs(); // creates data and data/reports if missing
File file = new File(folder, "summary.txt");
if (file.createNewFile()) {
System.out.println("Created " + file.getPath());
}
}
}The modern way
Creating a file with java.nio.file
import java.nio.file.Path;
import java.nio.file.Files;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
Path path = Path.of("greeting.txt");
if (Files.notExists(path)) {
Files.createFile(path);
System.out.println("Created " + path);
} else {
System.out.println("Already there.");
}
}
}- createNewFile never overwrites and returns a boolean telling you what happened.
- Create parent folders with mkdirs before creating a file inside them.
- Files.createFile throws if the file already exists, so guard against it.
- All of these can throw IOException and must be handled.