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();


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM