如果不存在,则创建文件和中间目录 [英] Creating file and intermediate directories if does not exist

查看:150
本文介绍了如果不存在,则创建文件和中间目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



举例来说,文件位置是指C:\ user\如果(!file.exists()){$ b $ Desktop $ \\ b试试{
file.createNewFile();
} catch(IOException ioe){
ioe.printStackTrace();
return;






$ b

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



/ p>


  • 有时候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;




$ b $ p $或者有比这更明确的解决方案吗?你可以做这样的事情:
$ b $ b

file.getParentFile()。mkdirs();


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


更新



pre $ if(file.getParentFile试试
{
file.createNewFile();

catch(IOException ioe)
{
ioe.printStackTrace();
return;

}其他{
/ **无法创建目录和|或全部|一些不存在的父目录** /
}


I want to create a file if and only if that file does not exist.

As an example file location is referring to "C:\user\Desktop\dir1\dir2\filename.txt"

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

Unfortunately the above code is failing, as the dir1 and dir2 does not exist.

For my case

  • Sometime the dir1 and dir2 may exist and sometime they may not exist.
  • I do not want to overwrite the contents of these intermediate directories if they already exists,

How to check this cleanly?

I was thinking to add the following check to handle this condition:

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;
    }
}

Or there is a clearer solution than this?

解决方案

you can do something of this sort:

file.getParentFile().mkdirs();

Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. Note that if this operation fails it may have succeeded in creating some of the necessary parent directories.

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 **/
}

这篇关于如果不存在,则创建文件和中间目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆