文件操作工具类
package com.util;
import java.io.File;
public class FileUtils {
public static boolean delete(String fileName) {
File file = new File(fileName);
if (!file.exists()) {
System.out.println("删除文件失败:" + fileName + "不存在!");
return false;
} else {
if (file.isFile())
return deleteFile(fileName);
else
return deleteDirectory(fileName);
}
}
public static boolean deleteFile(String fileName) {
File file = new File(fileName);
if (file.exists() && file.isFile()) {
if (file.delete()) {
System.out.println("删除单个文件" + fileName + "成功!");
return true;
} else {
System.out.println("删除单个文件" + fileName + "失败!");
return false;
}
} else {
System.out.println("删除单个文件失败:" + fileName + "不存在!");
return false;
}
}
public static boolean deleteDirectory(String dir) {
System.out.println("需要删除的路径为:" + dir);
if (!dir.endsWith(File.separator))
dir = dir + File.separator;
File dirFile = new File(dir);
if ((!dirFile.exists()) || (!dirFile.isDirectory())) {
System.out.println("删除目录失败:" + dir + "不存在!");
return false;
}
boolean flag = true;
File[] files = dirFile.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isFile()) {
flag = FileUtils.deleteFile(files[i].getAbsolutePath());
if (!flag)
break;
}
else if (files[i].isDirectory()) {
flag = FileUtils.deleteDirectory(files[i]
.getAbsolutePath());
if (!flag)
break;
}
}
if (!flag) {
System.out.println("删除目录失败!");
return false;
}
if (dirFile.delete()) {
System.out.println("删除目录" + dir + "成功!");
return true;
} else {
return false;
}
}
public static void createFile(String filePath) throws Exception {
if (filePath == null || filePath.trim().length() == 0) {
return;
}
File fp = new File(filePath);
if (!fp.exists()) {
fp.mkdirs();
}
}
}