How to check if a folder exists

后端 未结 10 1831
滥情空心
滥情空心 2020-11-28 21:21

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,

相关标签:
10条回答
  • 2020-11-28 21:45

    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()) {
       ...
    }
    
    0 讨论(0)
  • 2020-11-28 21:45

    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");
            }
    
    0 讨论(0)
  • 2020-11-28 21:50

    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());
      }
    }
    
    0 讨论(0)
  • 2020-11-28 21:53
    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;
      }
    
    }
    
    0 讨论(0)
  • 2020-11-28 21:54

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

    0 讨论(0)
  • 2020-11-28 21:57
    File sourceLoc=new File("/a/b/c/folderName");
    boolean isFolderExisted=false;
    sourceLoc.exists()==true?sourceLoc.isDirectory()==true?isFolderExisted=true:isFolderExisted=false:isFolderExisted=false;
    
    0 讨论(0)
提交回复
热议问题