241

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());
    }
}
Abra
  • 19,142
  • 7
  • 29
  • 41
Al Phaba
  • 6,545
  • 12
  • 51
  • 83
  • 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 '13 at 13:30
  • possible duplicate of [Java 7 new IO API - Paths.exists](http://stackoverflow.com/questions/5127537/java-7-new-io-api-paths-exists) – Mr_and_Mrs_D Jul 07 '14 at 21:00

10 Answers10

320

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)) {
Jesper
  • 202,709
  • 46
  • 318
  • 350
  • 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 '13 at 13:34
  • O_O @Sanchit do you have some strong argument to say it? – richardaum Mar 19 '14 at 15:15
  • 8
    The documentation says so. :) [link](http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html) Check the notExists method can't really link it properly. – Sanchit Mar 19 '14 at 16:37
  • 16
    Files.isDirectory(Path, LinkOption); – Kanagavelu Sugumar Nov 21 '14 at 08:10
  • @PhilipRego Yes there is, see the [API docs](http://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#exists-java.nio.file.Path-java.nio.file.LinkOption...-). Note that the second parameter is a varargs parameter, which means you can supply 0 or more values for the second parameter. – Jesper May 17 '17 at 19:33
  • @Sanchit Why not using `!Files.exists(path)`? What advantage `Files.notExists` has? – LoMaPh Nov 09 '18 at 21:41
  • 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 '18 at 11:15
  • @Jesper You says they are 100% the same thing and on the next sentence you point out the difference! They are not the same. The fact that two methods exist is a clear indicator of this. exists() will return true if the file exists. It will return false if it does not exist or it can't tell. The notExists() method will return true if the file does exists. It will return false if it exists or it can't tell. – cquezel Aug 09 '20 at 14:46
  • @cquezel look at my comment above, I wrote: "... are **not** 100% the same thing" – Jesper Aug 09 '20 at 15:29
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()) {
   ...
}
Chris Cooper
  • 4,982
  • 1
  • 17
  • 27
  • 46
    correct answer, but a small notice: `if(f.isDirectory()) {...}` would be enough, as it checks also existence. – G. Demecki Jan 21 '15 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 02 '17 at 22:27
  • @DoronGold Thank you for your timely response! I'll take what you said onboard. – Chris Cooper Feb 10 '21 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.

Fernando Correia
  • 21,803
  • 13
  • 83
  • 116
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");
        }
Jose Medina
  • 101
  • 1
  • 2
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());
  }
}
El Bert
  • 2,958
  • 1
  • 28
  • 36
5

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

Dan Mandel
  • 637
  • 1
  • 8
  • 26
kanbagoly
  • 319
  • 3
  • 9
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;
  }

}
Nadhu
  • 419
  • 6
  • 5
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      
        }
    }
}
Akib Bagwan
  • 138
  • 1
  • 2
  • 14
  • 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 '17 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

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
}
MasterHD
  • 2,264
  • 1
  • 32
  • 41