Explain Codes LogoExplain Codes Logo

How to check if a folder exists?

java
file-system
directory-structure
symbolic-links
Nikita BarsukovbyNikita Barsukov·Oct 24, 2024
TLDR

Quickly check a folder's existence in Java with Files.exists() from java.nio.file.Files:

boolean exists = Files.exists(Paths.get("/path/to/folder"));

Then apply Files.isDirectory() to ensure the path leads to a directory:

boolean isDirectory = Files.isDirectory(Paths.get("/path/to/folder"));

When you're checking a path, symbolic links may behave a bit like hide-and-seek champions, pointing elsewhere. Control the symlink-effect with LinkOption.NOFOLLOW_LINKS when calling Files.exists:

// The hide-and-seek game begins! boolean folderExists = Files.exists(folderPath, LinkOption.NOFOLLOW_LINKS);

The non-existence conundrum

Non-existence might be philosophical, but it's also a Java thing. When Files.exists() returns false, it not only tells you that the folder seems non-existent, but possibly also that it's simply unreachable:

// Queries the universe: "To exist or not to exist?" boolean folderDoesNotExist = Files.notExists(folderPath);

And creating missing directories becomes your own invention of existence:

if (Files.notExists(folderPath)) { Files.createDirectories(folderPath); // The PHP developers won't believe us, but we just created something from nothing! }

Peeking into file iteration

When you're not simply checking, but listing contents, DirectoryStream pulls out its practical iteration toolkit. Always remember to use a try-with-resources block to guarantee automatic closure:

Path dir = Paths.get("/path/to/folder"); // Ready... set... iterate! try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) { for (Path file : stream) { // Give each file some love. } } catch (IOException e) { // Pay a visit to the exception handler. }

An at-nod to File class

File class then steps in, polishing its bit-old but shining utility belt of methodologies. To check a folder, combine exists() and isDirectory():

File folder = new File("/path/to/folder"); // If the folder retrieval was a jazz song, this line would be the climax. if (folder.exists() && folder.isDirectory()) { // Robert is your father's brother! The folder exists. }

Error guarding and chronicling

Handling errors might not be a knight's job, but surely needs a heroic spirit. Proper error handling preempts potential IOExceptions:

// Alert! Exception incoming. try { Path folderPath = Paths.get("/path/to/folder"); if (!Files.exists(folderPath)) { Files.createDirectory(folderPath); } } catch (IOException e) { // Exception: 1 Danger: 0 }

Performing logging can be like maintaining a diary for your code – keeping track of checks, misses, and hits:

Path folderPath = Paths.get("/path/to/folder"); if (Files.exists(folderPath)) { // Sherlocking our way through existence. System.out.println("Folder exists: " + folderPath); }

Tackling edge cases

The read access assurance

Checking for existence is Step 1, but what about permissions? The access saga continues:

Path folderPath = Paths.get("/path/to/folder"); boolean canRead = Files.isReadable(folderPath); // On a quest for readable folders! if (Files.exists(folderPath) && canRead) { // We've got a winner! }

Symbolic links: Always pointing, but what if there's no place to point to?

Path symlinkPath = Paths.get("/path/to/symlink"); boolean isSymbolicLink = Files.isSymbolicLink(symlinkPath); if (isSymbolicLink && Files.exists(Files.readSymbolicLink(symlinkPath))) { // Found a symbolic link that points to a real place. This isn't Narnia! }

The hierarchy summoning

Creating a directory is magical, but creating a multi-level directory structure feels straight out of a wizard's book:

Path directoriesPath = Paths.get("/path/to/deep/directory/structure"); // In the wise words of Dumbledore: Files.createDirectories(directoriesPath); // "Help will always be given at Hog... umm StackOverflow, to those who create directories."