java.io.ioexception: 系统找不到指定的路径。

场景:java.io.IOException: 系统找不到指定的路径,解决办法

java.io.IOException: 系统找不到指定的路径,解决方法!
点击右边红色标题查看本文完整版:java.io.IOException: 系统找不到指定的路径,解决方法!

多线程的文件输出,每个线程负责写一个文件,如果文件不存在,则创建一个,在多次的测试中偶尔会出现这样的异常:


java.io.IOException: 系统找不到指定的路径。
at java.io.WinNTFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:850)

具体的写文件的操作如下:

String path= "AAA/BBB/CCC/DDD/EEE/FFF/XXX.js " 相对路径,文件路径的层次比较深

接下来,思路是先创建文件夹,然后再创建文件,接下来再写文件
String dir = path.substring(0,path.lastIndexOf( '/ ')); 取出目录
File file = new File(dir);
if(!file.exists()) 目录不存在,则创建相应的目录
file.mkdirs();
File file2 = new File(path);
if(!file2.exists()) 接下来创建具体文件
file2.createNewFile(); 就是在这个点抛出异常

------解决方法--------------------
//目录创建不一定成功的。
boolean success = file.mkdirs();
if(success)
{
File file2 = new File(path);
if(!file2.exists())
file2.createNewFile();
}
------解决方法--------------------
if (!file2.exists())
try {
file2.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}