[求助]为何File的createNewFile不起作用?

dl348 2015-08-26 09:39:47
public static void main(String[] args) {
File file=new File("resources");
if(!file.exists()){
file.mkdir();
System.out.println("ok");}
System.out.println(file.getAbsolutePath());
File file2=new File(file,"one.dat");
if(!file2.exists()){
try{
file.createNewFile();
System.out.println("file2 created");
}
catch (IOException e){
System.out.println("error");
}
System.out.println(file2.getAbsolutePath());}
System.out.println(file2.exists());
}

经查硬盘,创建了resources文件夹,但并没有创建one.dat,并且输出结果是:
E:\javaProject\demo\resources
file2 created
E:\javaProject\demo\resources\one.dat
false

java的getAbsolutePath可以获取one.dat的路径,但是exists却判断one.dat不存在(确实也不存在)

请问问题出在哪里,我该如何解决?
...全文
423 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
dl348 2016-03-10
  • 打赏
  • 举报
回复
是我粗心了,谢谢
  • 打赏
  • 举报
回复
	public static void main(String[] args) {
		File file = new File("resources");
		if (!file.exists()) {
			file.mkdir();
			System.out.println("ok");
		}
		System.out.println(file.getAbsolutePath());
		File file2 = new File(file, "one.dat");
		if (!file2.exists()) {
			try {
				file2.createNewFile();//file2 不是file
				System.out.println("file2 created");
			} catch (IOException e) {
				System.out.println("error");
			}
			System.out.println(file2.getAbsolutePath());
		}
		System.out.println(file2.exists());
	}
0萌萌哒0 2015-08-26
  • 打赏
  • 举报
回复
你好,是你的代码写错了,应该是file2.createNewFile()

62,614

社区成员

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

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