1. Creating files
You often have to create files programmatically: for logs, temporary data, report export, data import, saving settings, and much more. In Java, as you have probably guessed, it’s best to use the modern API — java.nio.file.
Main tool: Files.createFile(Path)
This method creates a new file at the given path. If the file already exists, an exception will be thrown.
Example: create a text file in the current directory
import java.nio.file.*;
public class CreateFileExample {
public static void main(String[] args) {
Path path = Path.of("hello.txt");
try {
Files.createFile(path);
System.out.println("File created: " + path.toAbsolutePath());
} catch (FileAlreadyExistsException e) {
System.out.println("File already exists: " + path);
} catch (Exception e) {
System.out.println("Error creating file: " + e.getMessage());
}
}
}
Note:
Files.createFile throws FileAlreadyExistsException if the file already exists. That’s why it’s common to check for existence before creating a file.
Checking whether a file exists
Path path = Path.of("hello.txt");
if (!Files.exists(path)) {
Files.createFile(path);
}
Tip:
Checking for existence is not protection against race conditions between threads, but for most user scenarios it’s good enough.
In short: what happens when creating a file?
- If the file does not exist and the path is valid — a new empty file is created.
- If the file already exists — an exception is thrown.
- If the path is invalid, you lack permissions, or the directory does not exist — a different exception will be thrown (IOException, NoSuchFileException, etc.).
2. Creating directories
Difference between Files.createDirectory and Files.createDirectories
- Files.createDirectory(Path) — creates only one directory. If the parent directory does not exist — it fails.
- Files.createDirectories(Path) — creates the entire chain of missing directories (like a wizard building a staircase right under your feet).
Example: create a single directory
Path dir = Path.of("data");
try {
Files.createDirectory(dir);
System.out.println("Directory created: " + dir.toAbsolutePath());
} catch (FileAlreadyExistsException e) {
System.out.println("Directory already exists: " + dir);
} catch (Exception e) {
System.out.println("Error creating directory: " + e.getMessage());
}
Example: create a nested directory structure
Path nested = Path.of("data/reports/2024");
try {
Files.createDirectories(nested);
System.out.println("Directory structure created: " + nested.toAbsolutePath());
} catch (Exception e) {
System.out.println("Error creating structure: " + e.getMessage());
}
Note: if some of the directories already exist, createDirectories doesn’t mind — it simply creates the missing ones. If you use createDirectory for a nested directory while the parent doesn’t exist yet — it will fail.
Table: comparison of directory creation methods
| Method | Creates only one directory | Creates nested directories | Does not fail if some parts already exist |
|---|---|---|---|
|
✔ | ✗ | ✗ |
|
✔ | ✔ | ✔ |
3. Deleting files
Deleting files is almost like taking out the trash: the main thing is not to throw out something you still need! In Java there are two primary methods:
- Files.delete(Path) — deletes a file or an empty directory. If the file doesn’t exist — it throws an exception.
- Files.deleteIfExists(Path) — deletes a file, but if it wasn’t there — it quietly does nothing.
Example: delete a temporary file
Path tempFile = Path.of("temp.txt");
try {
Files.delete(tempFile);
System.out.println("File deleted: " + tempFile);
} catch (NoSuchFileException e) {
System.out.println("File not found: " + tempFile);
} catch (DirectoryNotEmptyException e) {
System.out.println("Directory not empty: " + tempFile);
} catch (Exception e) {
System.out.println("Error deleting: " + e.getMessage());
}
Safer option
boolean deleted = Files.deleteIfExists(tempFile);
if (deleted) {
System.out.println("The file was deleted.");
} else {
System.out.println("File not found — nothing to delete.");
}
Important!
- If the file is open in another program — an exception may be thrown (for example, on Windows).
- If you try to delete a directory that isn’t empty — you’ll get DirectoryNotEmptyException.
4. Deleting directories
We delete directories in Java about the same way as files. With one nuance: the standard methods only delete empty directories.
Example: delete an empty directory
Path emptyDir = Path.of("empty_folder");
try {
Files.delete(emptyDir);
System.out.println("Directory deleted: " + emptyDir);
} catch (DirectoryNotEmptyException e) {
System.out.println("Directory not empty: " + emptyDir);
} catch (NoSuchFileException e) {
System.out.println("Directory not found: " + emptyDir);
} catch (Exception e) {
System.out.println("Error deleting directory: " + e.getMessage());
}
What about non-empty directories?
To delete non-empty directories, you need to recursively delete all nested files and subdirectories. This deserves its own lecture (and a separate adventure), but if you can’t wait, here’s the code — study it and try to reproduce:
import java.nio.file.*;
import java.io.IOException;
public class DeleteDirectoryRecursively {
public static void deleteRecursively(Path path) throws IOException {
if (Files.isDirectory(path)) {
try (var entries = Files.list(path)) {
for (Path entry : entries.toList()) {
deleteRecursively(entry);
}
}
}
Files.delete(path);
}
}
Caution:
This code will delete everything inside the directory! Use with care.
5. Practical tips
Check existence before deletion
if (Files.exists(path)) {
Files.delete(path);
} else {
System.out.println("File/directory does not exist.");
}
But if you use deleteIfExists, this isn’t necessary.
Exception handling
When working with files, we often run into surprises. Java throws different exceptions for that:
- NoSuchFileException — the file or directory was not found. For example, you’re trying to open something that has already been deleted.
- DirectoryNotEmptyException — you want to delete a directory, but it still contains something.
- IOException — a generic warning: something went wrong. The reason may vary — no access rights, the file is locked by another program, the path is invalid.
Visual diagram: core methods
+-------------------+ +--------------------+
| Files.createFile | ----> | New file |
+-------------------+ +--------------------+
+---------------------+ +--------------------+
| Files.createDirectory|----> | New directory |
+---------------------+ +--------------------+
+-------------------+ +--------------------+
| Files.delete | ----> | File/dir deleted |
+-------------------+ +--------------------+
(but only if the directory is empty!)
6. Common mistakes when creating and deleting files and directories
Error #1: Attempting to create a file/directory that already exists. The methods Files.createFile and Files.createDirectory throw an exception if the target already exists. Solution — check for existence in advance or catch the exception.
Error #2: Trying to create a nested directory with createDirectory while the parent doesn’t exist yet. In this case you’ll get NoSuchFileException. Use createDirectories to create the full chain.
Error #3: Trying to delete a non-empty directory with Files.delete. You’ll get DirectoryNotEmptyException. Deleting non-empty directories requires recursion.
Error #4: No permission to create/delete in the specified directory. AccessDeniedException or IOException will be thrown. Run the program with the required permissions or use accessible directories.
Error #5: The file is in use by another process. On Windows (and sometimes on other OSes) you can’t delete a file if it is open in another program. You’ll get IOException. Close all applications using the file before deletion.
Error #6: Using relative paths without understanding “where you are.” The file is created somewhere you didn’t expect. To be sure, use toAbsolutePath() and print the path.
GO TO FULL VERSION