File类的createNewFile()方法为什么抛出了异常?
import java.io.*;
class FileCons {
public static void main(String[] args) {
try{
File f1 = new File( "d:\\ ");
File f2 = new File( "d:\\ ", "zhaozhao ");
File f3 = new File( "f2 ", "sss.txt ");
File f4 = new File( "File1.java ");
File f5 = new File( "asdf+?12/ ");
if (f1.exists())
System.out.println(f1 + " exists ");
else System.out.println(f1 + " is not exists ");
System.out.println( "Path of F1 is " + f1.getPath());
if (f2.exists())
System.out.println(f2 + " exists ");
else System.out.println(f2 + " is not exists ");
/*从答案中我们可以看出d:\zhaozhao这个文件夹并不存在
/*下面我们将创建文件夹zhaozhao*/
f2.mkdir() ;
if (f2.exists())
System.out.println( "After mkdir() , "+f2 + " exists ");
else System.out.println(f2 + " is still not exists ");
if (f3.exists())
System.out.println(f3 + " exists ");
else { System.out.println(f3 + "is not exists "); /*由这句话我们知道f3.exits()
没有抛出异常*/
f3.createNewFile();
/*d:\zhaozhao文件夹已经存在,为什么仍然无法在那个文件夹下创建文件sss.txt,
*f3.createNewFile()抛出异常*/
System.out.println( "F3 was created! ");
}
if(f4.exists())
{ System.out.println(f4+ " exists,the AbsolutePath is "+f4.getAbsolutePath());
}
else{
f4.createNewFile();
System.out.println( "F4 was created! ");
}
if(f5.exists())
System.out.println(f5+ "exists ");
else{
f5.createNewFile();
System.out.println( "F5 was created! ");
}
} catch(java.io.IOException e) {
e.printStackTrace();
}
}
}
运行结果:
d:\ exit
Path of F1 is d:\
d:\zhaozhao exits
After mkdir(),d:\zhaozhao exists.
f2\sss.txtis not exists
java.io.IOException:系统找不到指定的路径。
at java.io.WinNTFileSystem.createFileExclusively <Native Method>
at java.io.File.createNewFile <File.java:828>
at FileCons.main <FileCons4.java:32>
疑惑:
下面是运行结果,我不明白d:\zhaozhao已经存在了,为什么 f3.createNewFile()会抛出异常,按理说应该建一个文件d:\zhaozhao\sss.txt?
[解决办法]
如果没有写磁盘的权限,或者相同文件已经存在,就会抛出异常
[解决办法]
File f3 = new File( "f2 ", "sss.txt ");
这句是什么意思啊? \f2\sss.txt?
System.out.println(f1 + " exists ");
这句真的能打印出来 “d:\ exit”吗?
File f4 = new File( "File1.java ");
这句应该把路径也加上
File f5 = new File( "asdf+?12/ ");
这个路径名不合法
你把程序跑一遍,改一改再贴上来吧
[解决办法]
你的路径好象不对吧?
[解决办法]
路径不对