Java 在给定路径上创建文件,所在文件夹不存在时,如何正确创建。

Posted 小半夏

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java 在给定路径上创建文件,所在文件夹不存在时,如何正确创建。相关的知识,希望对你有一定的参考价值。

原文链接:https://www.cnblogs.com/shuilangyizu/p/9841640.html   (侵删)

String strPath = "E:\\\\a\\\\aa\\\\aaa.txt";
File file = new File(strPath);
if(!file.exists())){
    file.createNewFile();
}

 

这段代码,如果 E:\\a\\aa\\ 文件夹不存在,会报错。

String strPath = "E:\\\\a\\\\aa\\\\aaa.txt";
File file = new File(strPath);
if(!file.exists())){
    file.file.mkdirs();
}

这段代码,会创建文件夹 E:\\\\a\\\\aa\\\\aaa.txt\\。

  String strPath = "E:\\\\a\\\\aa\\\\aaa.txt";
File file = new File(strPath);
File fileParent = file.getParentFile();
if(!fileParent.exists()){
    fileParent.mkdirs();
}
file.createNewFile();

以上是关于Java 在给定路径上创建文件,所在文件夹不存在时,如何正确创建。的主要内容,如果未能解决你的问题,请参考以下文章