2014-02-11 88 views
1

当且仅当该文件不存在时才想创建文件。如果不存在,创建文件和中间目录

作为一例文件位置指的是 “C:\用户\桌面\ DIR1 \ DIR2 \ FILENAME.TXT”

if (!file.exists()) { 
    try { 
     file.createNewFile(); 
    } catch(IOException ioe) {     
     ioe.printStackTrace(); 
     return; 
    } 
} 

不幸的是,上面的代码失败,因为dir1dir2不存在。

对于我而言

  • 某个时刻DIR1和DIR2可能存在并且有时他们可能不存在。
  • 我不希望覆盖这些中间目录的内容,如果他们已经存在,

如何干净地检查这个?

我想补充以下检查以处理这种情况:

if (!file.getParentFile().getParentFile().exists()) { 
    file.getParentFile().getParentFile().mkdirs(); 
} 
if (!file.getParentFile().exists()) { 
    file.getParentFile().mkdirs(); 
} 

if (!file.exists()) {        
    try { 
     file.createNewFile(); 
    } catch(IOException ioe) { 
     ioe.printStackTrace(); 
     return; 
    } 
} 

或者有比这更清晰的解决方案?

+2

你不需要检查'exists()'。 'mkdirs()'只有在不存在的情况下才会创建目录。 –

+0

如果该目录已经存在,我将再次调用mkdirs()会发生什么? – Exploring

+2

它会跳过。它不会创建一个新目录。检查该方法的文档。它清楚地提到了这件事。 –

回答

5

,你可以做这样的事情:

file.getParentFile().mkdirs();

创建此抽象路径名指定的目录,包括所有必需但不存在的父目录。请注意,如果此操作失败,则可能会成功创建一些必需的父目录。

更新

if (file.getParentFile().exists || file.getParentFile().mkdirs()){ 
     try 
     { 
      file.createNewFile(); 
     } 
     catch(IOException ioe) 
     { 
      ioe.printStackTrace(); 
      return; 
     } 
} else { 
    /** could not create directory and|or all|some nonexistent parent directories **/ 
} 
+0

我已经在我的解决方案中提到过这个问题。所以这不是一个答案。 – Exploring

+1

user1631616发布的代码不正确。 file.getParentFile()。当目录已经存在时,mkdirs()将返回false。这也可以从文档中验证。该文件提到 - 当且仅当该目录已经创建,以及所有必要的父目录;否则为假“。 – Exploring

+0

@Baishakh是的,你是正确的,它只会在创建目录时返回true。我已添加检查存在。你的编辑盲目地做'file.getParentFile()。mkdirs()'是一个不好的做法,因为它仍然可能无法创建所有目录 –

1

当心File.exists()检查文件目录的存在。

相反的:

if(!file.exists()) {        
    try { 
     file.createNewFile(); 
    } catch(IOException ioe) { 
     ioe.printStackTrace(); 
     return; 
    } 
} 

你应该明确地检查,如果该文件是一个文件可能有相同名称的目录:

if(!file.isFile()) {        
    try { 
     file.createNewFile(); 
    } catch(IOException ioe) { 
     ioe.printStackTrace(); 
     return; 
    } 
} 

同样的,你应该检查父文件是一个目录:

if (!file.getParentFile().getParentFile().isDirectory()) { ... } 
相关问题