Check, create and delete files and folders
35 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)The Files class turns a Path into real work on the disk: check what is there, create files and folders, and delete them. When something goes wrong, it throws an exception whose name says exactly what.
exists, isRegularFile, isDirectory and isReadable
Files.exists(path) returns true when something is at that path, a file or a folder. isRegularFile is true only for a normal file, and isDirectory only for a folder (Java calls a folder a directory).
Example 1 · Checking what is at a path
import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.util.List;
public class CheckDemo { static void report(Path p) { System.out.println(p.getFileName() + ": exists=" + Files.exists(p) + ", file=" + Files.isRegularFile(p) + ", folder=" + Files.isDirectory(p) + ", readable=" + Files.isReadable(p)); }
public static void main(String[] args) throws IOException { Path folder = Path.of("check-demo"); Path file = folder.resolve("attendance.csv"); Path missing = folder.resolve("missing.csv"); Files.createDirectory(folder); // next section Files.writeString(file, "Roll,Present");
for (Path p : List.of(folder, file, missing)) { report(p); } System.out.println("notExists(missing.csv)? " + Files.notExists(missing));
Files.delete(file); Files.delete(folder); }}check-demo: exists=true, file=false, folder=true, readable=true attendance.csv: exists=true, file=true, folder=false, readable=true missing.csv: exists=false, file=false, folder=false, readable=false notExists(missing.csv)? true
What this code does
existsistruefor both the folder and the file;isRegularFileandisDirectorytell them apart.- For the missing path every check is simply
false, with no exception.notExistsistruebecause Java could confirm that nothing is there.
isReadable and isWritable tell you whether your program may read or change it.
All of these return false for a missing path; none of them throws. Files.notExists(path) is not always the opposite of exists: when Java cannot find out, for example because a folder on the way is locked, both return false.
createFile, createDirectory and createDirectories
Files.createFile(path) makes a new, empty file. Files.createDirectory(path) makes one folder. Both throw FileAlreadyExistsException if the name is taken, and NoSuchFileException if the parent folder does not exist.
Example 2 · Creating files and folders
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 CreateDemo { public static void main(String[] args) throws IOException { Path hostel = Path.of("hostel"); Path room = hostel.resolve("block-b").resolve("room-204");
try { Files.createDirectory(room); } catch (NoSuchFileException e) { System.out.println("createDirectory: parent folders are missing"); }
Files.createDirectories(room); System.out.println("createDirectories made " + room.getFileName() + ": " + Files.isDirectory(room)); Files.createDirectories(room); System.out.println("Called again: no error");
Path list = room.resolve("inventory.txt"); Files.createFile(list); System.out.println("New file size: " + Files.size(list)); try { Files.createFile(list); } catch (FileAlreadyExistsException e) { System.out.println("createFile again: " + e.getClass().getSimpleName()); }
Files.delete(list); // clean up, deepest first Files.delete(room); Files.delete(room.getParent()); Files.delete(hostel); }}createDirectory: parent folders are missing createDirectories made room-204: true Called again: no error New file size: 0 createFile again: FileAlreadyExistsException
What this code does
createDirectorymakes only the last folder, so it fails whilehostelandblock-bare missing.createDirectoriesbuilds the whole chain and is happy to be called again.createFilemakes an empty file (size 0) and refuses to touch an existing one, so it never overwrites data by accident.
Files.createDirectories(path) makes every missing folder on the way, like a whole hostel/block-b/room-204 chain in one call. It does nothing if the folder already exists, which makes it safe to call every time a program starts.
Path they created, so you can write Path dir = Files.createDirectories(Path.of("reports"));.delete versus deleteIfExists
Files.delete(path) removes a file or an empty folder. If nothing is there, it throws NoSuchFileException. Files.deleteIfExists(path) does the same but returns false instead of throwing when nothing is there, and true when it deleted something.
Example 3 · delete, deleteIfExists and a folder that is not empty
import java.io.IOException;import java.nio.file.DirectoryNotEmptyException;import java.nio.file.Files;import java.nio.file.NoSuchFileException;import java.nio.file.Path;
public class DeleteDemo { public static void main(String[] args) throws IOException { Path notes = Path.of("old-notes.txt"); Files.writeString(notes, "Unit 1 notes"); Files.delete(notes); System.out.println("Deleted once");
try { Files.delete(notes); } catch (NoSuchFileException e) { System.out.println("delete again: NoSuchFileException for " + e.getFile()); } System.out.println("deleteIfExists: " + Files.deleteIfExists(notes));
Path drafts = Path.of("project-drafts"); Files.createDirectory(drafts); Files.writeString(drafts.resolve("v1.txt"), "draft"); try { Files.delete(drafts); } catch (DirectoryNotEmptyException e) { System.out.println("Not empty: " + e.getFile()); } Files.delete(drafts.resolve("v1.txt")); System.out.println("Empty folder deleted: " + Files.deleteIfExists(drafts)); }}Deleted once delete again: NoSuchFileException for old-notes.txt deleteIfExists: false Not empty: project-drafts Empty folder deleted: true
What this code does
- A second
deletethrows because the file is gone;deleteIfExistsjust answersfalse. - A folder with a file inside cannot be deleted. After removing
v1.txt, the empty folder goes, anddeleteIfExistsreturnstrue.
Use delete when the file must exist, so a missing file is reported as a bug. Use deleteIfExists for clean-up, where "already gone" is fine. Neither one deletes a folder that still has something inside: that throws DirectoryNotEmptyException, so delete the contents first.
Fix the error
Fix the unreported IOException
Read the error, then pick the line that fixes it.
Round 1 of 2
deleteIfExists throws a checked exception. Pick the line that compiles.
Error
Cleanup.java:7: error: unreported exception IOException; must be caught or declared to be thrown
Files.deleteIfExists(old);
^NoSuchFileException, FileAlreadyExistsException and DirectoryNotEmptyException
These three exceptions are the ones you meet most. All are subclasses of FileSystemException, which is a subclass of IOException. getFile() returns the path that caused the problem as a String, and the message is usually that path.
Example 4 · One handler for the common file exceptions
import java.io.IOException;import java.nio.file.DirectoryNotEmptyException;import java.nio.file.FileAlreadyExistsException;import java.nio.file.Files;import java.nio.file.NoSuchFileException;import java.nio.file.Path;
interface FileAction { void run() throws IOException;}
public class FileErrorsDemo { static void attempt(String what, FileAction action) { try { action.run(); System.out.println(what + ": done"); } catch (NoSuchFileException e) { System.out.println(what + ": not found (" + Path.of(e.getFile()).getFileName() + ")"); } catch (FileAlreadyExistsException e) { System.out.println(what + ": already exists (" + Path.of(e.getFile()).getFileName() + ")"); } catch (DirectoryNotEmptyException e) { System.out.println(what + ": folder not empty (" + Path.of(e.getFile()).getFileName() + ")"); } catch (IOException e) { System.out.println(what + ": other problem: " + e); } }
public static void main(String[] args) { Path box = Path.of("box"); Path item = box.resolve("item.txt"); attempt("make box", () -> Files.createDirectory(box)); attempt("make box again", () -> Files.createDirectory(box)); attempt("add item", () -> Files.createFile(item)); attempt("delete box", () -> Files.delete(box)); attempt("delete item", () -> Files.delete(item)); attempt("delete item again", () -> Files.delete(item)); attempt("delete box", () -> Files.delete(box));
Class<?> c = NoSuchFileException.class; StringBuilder family = new StringBuilder(c.getSimpleName()); while (c != Exception.class) { c = c.getSuperclass(); family.append(" -> ").append(c.getSimpleName()); } System.out.println(family); }}make box: done make box again: already exists (box) add item: done delete box: folder not empty (box) delete item: done delete item again: not found (item.txt) delete box: done NoSuchFileException -> FileSystemException -> IOException -> Exception
What this code does
- The specific exceptions are caught before
IOException, so each problem gets its own message.getFile()names the path that caused it. - The last line walks up the class tree: all three exceptions are
FileSystemExceptions, and soIOExceptions, which is why the finalcatch (IOException e)would also catch them.
Example 5 · Fest registrations without a check-then-act race
import java.io.IOException;import java.nio.file.FileAlreadyExistsException;import java.nio.file.Files;import java.nio.file.Path;import java.util.ArrayList;import java.util.List;
public class FestRegistrationDemo { public static void main(String[] args) throws IOException { Path folder = Files.createDirectories(Path.of("fest-registrations")); List<Path> created = new ArrayList<>();
for (String team : List.of("code-ninjas", "byte-bandits", "code-ninjas", "pixel-pirates")) { Path entry = folder.resolve(team + ".txt"); try { Files.createFile(entry); created.add(entry); System.out.println("Registered " + team); } catch (FileAlreadyExistsException e) { System.out.println("Already registered: " + team); } } System.out.println("Total teams: " + created.size());
for (Path p : created) { Files.delete(p); } Files.delete(folder); }}Registered code-ninjas Registered byte-bandits Already registered: code-ninjas Registered pixel-pirates Total teams: 3
What this code does
createFileboth checks and creates in one step, so two registrations can never both win, even if two programs run at once. Anif (!Files.exists(entry))before it would leave a gap.createDirectoriesreturns the folder path, so it is created and stored in one line. The clean-up deletes the files first and the folder last.
Catch the specific ones first to give a clear message, then IOException for everything else, such as AccessDeniedException. Prefer "try it and catch" over "check, then act". Between exists returning false and your createFile, another program can create the file. createFile checks and creates in one step, so its exception is the reliable answer.
Next step
Check your understanding
11 quick questions