Al Phaba Al Phaba - 1 year ago 157
Java Question

How to check if a folder exists

I am playing a bit with the new Java 7 IO features, actually I trying to receive all the xml files of a folder. But this throws an exception when the folder does not exist, how can I check if the folder exists with the new IO?

public UpdateHandler(String release) {"searching for configuration files in folder " + release);
Path releaseFolder = Paths.get(release);
try(DirectoryStream<Path> stream = Files.newDirectoryStream(releaseFolder, "*.xml")){

for (Path entry: stream){"working on file " + entry.getFileName());
catch (IOException e){
log.error("error while retrieving update configuration files " + e.getMessage());


Answer Source

Using java.nio.file.Files:

Path path = ...;

if (Files.exists(path)) {
    // ...

You can optionally pass this method LinkOption values:

if (Files.exists(path, LinkOption.NOFOLLOW_LINKS)) {

There's also a method notExists:

if (Files.notExists(path)) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download