package com.apk.openUser.utils;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
//创建文件
public class OperateFileUtil {
public static void creatFile(String filePath, String fileName) {
File folder = new File(filePath);
//文件夹路径不存在
if (!folder.exists() && !folder.isDirectory()) {
System.out.println("文件夹路径不存在,创建路径:" + filePath);
folder.mkdirs();
} else {
System.out.println("文件夹路径存在:" + filePath);
}
// 如果文件不存在就创建
File file = new File(filePath + fileName);
if (!file.exists()) {
System.out.println("文件不存在,创建文件:" + filePath + fileName);
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("文件已存在,文件为:" + filePath + fileName);
}
}
public static boolean deletefile(String delpath) throws Exception {
Boolean bo = false;
try {
File file = new File(delpath);
// 当且仅当此抽象路径名表示的文件存在且 是一个目录时,返回 true
if (!file.exists()) {
System.out.println("删除文件失败:" + file + "不存在!");
bo = false;
} else {
if (!file.isDirectory()) {
file.delete();
} else if (file.isDirectory()) {
String[] filelist = file.list();
for (int i = 0; i < filelist.length; i++) {
//File.separator,自动识别系统中路径的分隔符/还是\\.
File delfile = new File(delpath +File.separator+ filelist[i]);
if (!delfile.isDirectory()) {
delfile.delete();
System.out.println(delfile.getAbsolutePath() + "删除文件成功");
} else if (delfile.isDirectory()) {
deletefile(delpath +File.separator+ filelist[i]);
}
}
System.out.println(file.getAbsolutePath() + "删除成功");
file.delete();
}
bo = true;
}
} catch (FileNotFoundException e) {
System.out.println("deletefile() Exception:" + e.getMessage());
}
return bo;
}
public static void main(String[] args) throws FileNotFoundException {
FileOutputStream outFile = null;
try {
/*creatFile(FILE_PATH, FILE_NAME);
outFile = new FileOutputStream(FILE_PATH + FILE_NAME);*/
String path = "D:/8F100";
System.out.println(deletefile(path));
//后续文件操作
} catch (Exception e) {
e.printStackTrace();
}
}
}