文件操作工具类:
/**
* 判断一个文件夹是否存在,若不存在则创建
* @param dirPath 文件夹路径 例:"D:\\dir"
*/
public static void createDocument(String dirPath){
File file = new File(dirPath);
//判断文件夹是否存在
if(!file.exists()){
//创建文件夹
boolean b = file.mkdirs();
//根据创建文件夹成功与否打印日志
if(b){
System.out.println("创建文件夹成功!");
}else{
System.out.println("创建文件夹失败!");
}
}
}
/**
* 判断一个文件是否存在
* @param filePath 文件的路径 举例:"D:\\test-utf.txt"
* @return true:表示文件存在 false:表示文件不存在
*/
public static boolean judgeFile(String filePath){
boolean b = true;
File file = new File(filePath);
//判断文件是否存在
if(!file.exists()){
//文件不存在
b = false;
}
return b;
}
/**
* 判断一个文件是否存在,若不存在则创建
* @param dirPath 文件的存放路径 例:"D:\\dir"
* @param fileName 文件名
*/
public static void createFile(String dirPath, String fileName){
try{
File dir = new File(dirPath);
//判断文件夹是否存在,若不存在则创建
if (!dir.exists()){
dir.mkdirs();
}
File file = new File(dirPath, fileName);
//判断文件夹是否存在
if(!file.exists()){
//创建文件夹
boolean b = file.createNewFile();
//根据创建文件夹成功与否打印日志
if(b){
System.out.println("创建文件成功!");
}else{
System.out.println("创建文件失败!");
}
}
}catch (Exception e){
e.printStackTrace();
}
}
main方法:
public static void main(String[] args) {
System.out.println("**************对文件夹进行判断和创建******************");
//第一步:判断文件夹是否存在
String dir1 = "D:\\TestDir1";
System.out.println("文件夹"+ dir1 +"是否存在:" + judgeFile(dir1));
//第二步: 创建文件夹
createDocument(dir1);
System.out.println("文件夹"+ dir1 +"是否存在:" + judgeFile(dir1));
System.out.println("**************对文件进行判断和创建******************");
//第一步:判断文件是否存在
String dir2 = "D:\\TestDir2";
String fileName = "test2.txt";
String filePath = dir2 + "\\" + fileName;
System.out.println("文件"+ filePath +"是否存在:" + judgeFile(filePath));
//第二步: 创建文件
createFile(dir2, fileName);
System.out.println("文件"+ filePath +"是否存在:" + judgeFile(filePath));
}
运行结果: