当且仅当该文件不存在时我想创建一个文件。
作为示例,文件位置指的是“C:\user\Desktop\dir1\dir2\filename.txt”
if (!file.exists()) {
try {
file.createNewFile();
} catch(IOException ioe) {
ioe.printStackTrace();
return;
}
}
不幸的是上面的代码失败了,因为dir1
and dir2
不存在。
对于我的情况
- 有时 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;
}
}
或者有比这更清晰的解决方案?
你可以做这样的事情:
file.getParentFile().mkdirs();
创建由此抽象路径名命名的目录,包括任何必要但不存在的父目录。请注意,如果此操作失败,则可能已成功创建一些必要的父目录。
Update
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 **/
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)