在磁盘D创建两个文件时,具体代码如下,程序是对着书上敲的,为啥会报错呢?
有无同行解答
import java.io.File;
import java.io.IOException;
public class Page166 {
public static void main(String[] args) throws IOException {
//磁盘下创建文件
File file = new File("D:\\hello\\demo.txt");
//如果存在这个文件就删除,否则就创建
if (file.exists()) {
file.delete();
} else {
System.out.println(file.createNewFile());
}
//在磁盘下创建一层目录,并且在目录下创建文件
File fileDemo = new File("D:\\hello1\\demo.txt");
//判断D:\hello1目录是否存在
if (!(fileDemo.getParentFile().exists())) {
fileDemo.getParentFile().mkdir();
}
//如果存在这个文件就删除,否则就创建
if (fileDemo.exists()) {
fileDemo.delete();
} else {
System.out.println(fileDemo.createNewFile());
}
}
}
运行结果:
Exception in thread "main" java.io.IOException: 系统找不到指定的路径。
at java.io.WinNTFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:1012)
at com.javajichu.Page166.main(Page166.java:14)
Process finished with exit code 1
我的java文件是放在D盘的: D:\untitled\src\com\包名中的,当我把要创建的文件位置放在这个位置时,程序没有报错,如下:
import java.io.File;
import java.io.IOException;
public class Page166 {
public static void main(String[] args) throws IOException {
//磁盘下创建文件
File file = new File("D:\\untitled1\\src\\com\\demo.txt"); //为本文件路径
//如果存在这个文件就删除,否则就创建
if (file.exists()) {
file.delete();
} else {
System.out.println(file.createNewFile());
}
//在磁盘下创建一层目录,并且在目录下创建文件
File fileDemo = new File("D:\\untitled1\\src\\com\\demo1.txt"); //为本文件路径
//判断D:\hello1目录是否存在
if (!(fileDemo.getParentFile().exists())) {
fileDemo.getParentFile().mkdir();
}
//如果存在这个文件就删除,否则就创建
if (fileDemo.exists()) {
fileDemo.delete();
} else {
System.out.println(fileDemo.createNewFile());
}
}
}
但这里我去除了hello和hello1文件夹,不然就会报错,是不能创建文件夹吗?
当我要完成上面的那种形式时,该怎么修改代码?