242

I am playing a bit with the new Java 7 IO features. Actually I am trying to retrieve all the XML files in a folder. However this throws an exception when the folder does not exist. How can I check if the folder exists using the new IO?

public UpdateHandler(String release) {
    log.info("searching for configuration files in folder " + release);
    Path releaseFolder = Paths.get(release);
    try(DirectoryStream<Path> stream = Files.newDirectoryStream(releaseFolder, "*.xml")){
    
        for (Path entry: stream){
            log.info("working on file " + entry.getFileName());
        }
    }
    catch (IOException e){
        log.error("error while retrieving update configuration files " + e.getMessage());
    }
}
2
  • 2
    I wonder why you would want to check whether the folder exists. Just because the folder exists when you checked does not mean the folder exists when you create the DirectoryStream, let alone when you iterate over the folder entries.
    – Oswald
    Mar 22, 2013 at 13:30
  • possible duplicate of Java 7 new IO API - Paths.exists Jul 7, 2014 at 21:00

10 Answers 10

322

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)) {
9
  • 40
    Also, note that both Files.exists(path) and Files.notExists(path) can return false at the same time! This means that Java could not determine if the path actually exists.
    – Sanchit
    Mar 22, 2013 at 13:34
  • O_O @Sanchit do you have some strong argument to say it?
    – richardaum
    Mar 19, 2014 at 15:15
  • 8
    The documentation says so. :) link Check the notExists method can't really link it properly.
    – Sanchit
    Mar 19, 2014 at 16:37
  • 16
    Files.isDirectory(Path, LinkOption); Nov 21, 2014 at 8:10
  • 3
    @LoMaPh !Files.exists(path) and Files.notExists(path) are not 100% the same thing. When Java cannot determine if a file exists, the first will return true and the second will return false.
    – Jesper
    Nov 10, 2018 at 11:15
238

Quite simple:

new File("/Path/To/File/or/Directory").exists();

And if you want to be certain it is a directory:

File f = new File("/Path/To/File/or/Directory");
if (f.exists() && f.isDirectory()) {
   ...
}
3
  • 46
    correct answer, but a small notice: if(f.isDirectory()) {...} would be enough, as it checks also existence.
    – G. Demecki
    Jan 21, 2015 at 11:33
  • 3
    This does not answer the OP's question. java.io.file is not part of "new Java 7 IO features" the OP is referring to. The java.nio.file package, which was introduced in Java 7, offers the Paths and Files classes. Other answers here correctly explain how to use these newer classes to solve the OPs problem.
    – Doron Gold
    Mar 2, 2017 at 22:27
  • @DoronGold Thank you for your timely response! I'll take what you said onboard. Feb 10, 2021 at 12:03
61

To check if a directory exists with the new IO:

if (Files.isDirectory(Paths.get("directory"))) {
  ...
}

isDirectory returns true if the file is a directory; false if the file does not exist, is not a directory, or it cannot be determined if the file is a directory or not.

See: documentation.

9

Generate a file from the string of your folder directory

String path="Folder directory";    
File file = new File(path);

and use method exist.
If you want to generate the folder you sould use mkdir()

if (!file.exists()) {
            System.out.print("No Folder");
            file.mkdir();
            System.out.print("Folder created");
        }
6

You need to transform your Path into a File and test for existence:

for(Path entry: stream){
  if(entry.toFile().exists()){
    log.info("working on file " + entry.getFileName());
  }
}
5

There is no need to separately call the exists() method, as isDirectory() implicitly checks whether the directory exists or not.

5
import java.io.File;
import java.nio.file.Paths;

public class Test
{

  public static void main(String[] args)
  {

    File file = new File("C:\\Temp");
    System.out.println("File Folder Exist" + isFileDirectoryExists(file));
    System.out.println("Directory Exists" + isDirectoryExists("C:\\Temp"));

  }

  public static boolean isFileDirectoryExists(File file)

  {
    if (file.exists())
    {
      return true;
    }
    return false;
  }

  public static boolean isDirectoryExists(String directoryPath)

  {
    if (!Paths.get(directoryPath).toFile().isDirectory())
    {
      return false;
    }
    return true;
  }

}
2

We can check files and thire Folders.

import java.io.*;
public class fileCheck
{
    public static void main(String arg[])
    {
        File f = new File("C:/AMD");
        if (f.exists() && f.isDirectory()) {
        System.out.println("Exists");
        //if the file is present then it will show the msg  
        }
        else{
        System.out.println("NOT Exists");
        //if the file is Not present then it will show the msg      
        }
    }
}
1
  • Seems doesn't work with a network shared file. Caught: org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'Z:\\tierWe bServices\Deploy\new.txt' with class 'org.codehaus.groovy.runtime.GStringImpl' to class 'java.nio.fi le.Path' org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'Z:\\tierWebService s\Deploy\new.txt' with class 'org.codehaus.groovy.runtime.GStringImpl' to class 'java.nio.file.Path'
    – Jirong Hu
    Jul 21, 2017 at 14:04
1
File sourceLoc=new File("/a/b/c/folderName");
boolean isFolderExisted=false;
sourceLoc.exists()==true?sourceLoc.isDirectory()==true?isFolderExisted=true:isFolderExisted=false:isFolderExisted=false;
1
  • sourceLoc.isDirectory() return boolean result. No need use "sourceLoc.isDirectory() == true" Jul 23, 2018 at 14:30
1

From SonarLint, if you already have the path, use path.toFile().exists() instead of Files.exists for better performance.

The Files.exists method has noticeably poor performance in JDK 8, and can slow an application significantly when used to check files that don't actually exist.

The same goes for Files.notExists, Files.isDirectory and Files.isRegularFile.

Noncompliant Code Example:

Path myPath;
if(java.nio.Files.exists(myPath)) {  // Noncompliant
    // do something
}

Compliant Solution:

Path myPath;
if(myPath.toFile().exists())) {
    // do something
}

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.