创建文件的三种方式
package file;
import java.io.File;
import java.io.IOException;
public class File01 {
public static void main(String[] args) {
//创建文件
//方法一 File(String pathname) 文件路径
/*String filepath = "F:\\程序作业\\方式一创建的文件.txt";
File file = new File(filepath);
try {
file.createNewFile();
System.out.println("文件创建成功");
} catch (IOException e) {
throw new RuntimeException(e);
}*/
//方式二 File(String parent, String child)
/* File parent = new File("F:\\程序作业");
File child = new File("F:\\程序作业","方式二创建的文件.txt");
try {
child.createNewFile();
System.out.println("文件创建成功");
} catch (IOException e) {
throw new RuntimeException(e);
}*/
//方式三
String filepath = "F:/程序作业/方式三创建的文件.txt";
File file = new File(filepath);
try {
file.createNewFile();
System.out.println("文件创建成功");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
结果
文件的删除
package file;
import java.io.File;
import java.lang.String;
public class File03 {
public static void main(String[] args) {
File file = new File("F:/程序作业/方式三创建的文件.txt");
if (file.exists()) {
if (file.delete()){
System.out.println("文件删除成功!");
}
else {
System.out.println("文件删除失败");
}
}else {
System.out.println("文件不存在");
}
}
}