File类的createNewFile()方法为什么抛出了异常?

Zhaothinking 2007-06-29 07:50:22
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?
...全文
2428 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
Zhaothinking 2007-07-03
  • 打赏
  • 举报
回复
谢谢大家的关注
Zhaothinking 2007-07-03
  • 打赏
  • 举报
回复
我找到问题的解决方法了
File(File parent, String child)
根据 parent 抽象路径名和 child 路径名字符串创建一个新 File 实例。
File(String pathname)
通过将给定路径名字符串转换成抽象路径名来创建一个新 File 实例。
File(String parent, String child)
根据 parent 路径名字符串和 child 路径名字符串创建一个新 File 实例。
File(URI uri)
通过将给定的 file: URI 转换成一个抽象路径名来创建一个新的 File 实例。


所以问题在于
File f3 = new File("f2","sss.txt");
应该是
File f3=new File(f2, ”sss.txt”);

其中File f4 = new File("File1.java");是正确的。是使用相对URI来创建一个File 对象引用。表示当前目录下的File.java文件引用


至于File f5 = new File("asdf+?12/"); 文件名字不对
stevenzuo 2007-07-01
  • 打赏
  • 举报
回复
你的路径好象不对吧?
奋斗并快乐着 2007-07-01
  • 打赏
  • 举报
回复
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/");
这个路径名不合法

你把程序跑一遍,改一改再贴上来吧
gwang119 2007-07-01
  • 打赏
  • 举报
回复
路径不对
zqrqq 2007-06-29
  • 打赏
  • 举报
回复
如果没有写磁盘的权限,或者相同文件已经存在,就会抛出异常

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧