【问题标题】:Determine whether a folder is present?确定文件夹是否存在?
【发布时间】:2011-02-12 03:38:39
【问题描述】:

如何确定文件或目录是否已在 Java 中创建?

如果还没有数据目录,我基本上想创建一个数据目录。

谢谢。

【问题讨论】:

    标签: java file filesystems io java-io


    【解决方案1】:

    可以调用File#exists()判断是否存在,如果不存在也可以直接调用File#mkdirs()自动创建整个路径。

    【讨论】:

      【解决方案2】:

      我通常使用这种技术:

          File folderLocation = new File("/blah/blah/mysystem/myfolder");
      
          if (folderLocation.exists()) {
              if (!folderLocation .isDirectory()) {
                  throw new IOException("File-system item with path [" + folderLocation.getAbsolutePath() + "] exists but is not a folder.");
              }                
          } else {
              if (!folderLocation.mkdirs()) {
                  throw new IOException("Could not create folder with path : " + folderLocation.getAbsolutePath());
              }
          }
      
          // we are guaranteed that the folder exists here
      

      【讨论】:

        猜你喜欢
        • 2013-07-04
        • 2011-08-03
        • 2011-09-06
        • 1970-01-01
        • 1970-01-01
        • 2011-05-25
        • 1970-01-01
        • 1970-01-01
        • 2021-02-16
        相关资源
        最近更新 更多