文件的创建
方式一:根据路径创建一个File对象
public static void creat01(){
String filePath = "d:/doc01.txt";
File file = new File(filePath);
try {
file.createNewFile();
System.out.println("文件创建成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
方式二:根据父目录文件+子路径创建
public static void creat02() {
File parentFile = new File("d:/");
String fileName = "doc02.txt";
File file = new File(parentFile, fileName);
try {
file.createNewFile();
System.out.println("文件创建成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
方式三:根据父目录+子路径创建
public static void creat03(){
String parentPath = "d:\\";
String fileName = "doc03.txt";
File file = new File(parentPath, fileName);
try {
file.createNewFile();
System.out.println("文件创建成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
文件的删除
使用delete删除一个文件或空目录
public static void deleteFile() {
String filePath = "d:/doc01.txt";
File file = new File(filePath);
if (file.exists()) {
if (file.delete()) {
System.out.println(filePath + ":删除成功!");
} else {
System.out.println(filePath + "删除失败!");
}
} else {
System.out.println("该文件不存在!");
}
}
public static void deleteFileOfCatalog() {
String filePath = "d:/Catalog";
File file = new File(filePath);
if (file.exists()) {
if (file.delete()) {
System.out.println(filePath + ":删除成功!");
} else {
System.out.println(filePath + "删除失败!");
}
} else {
System.out.println("该目录不存在!");
}
}
创建目录
public static void createDir() {
String dir = "d:/hello/word/demo01";
File file = new File(dir);
if (file.exists()) {
System.out.println(dir + ":存在!");
} else {
if (file.mkdirs()) {
System.out.println(dir + ":创建成功!");
} else {
System.out.println(dir + "创建失败!");
}
}
}