import java.io.File;
import java.io.IOException;
public class FileUtils {
/**
* @Title:createFile
* @description:新建文件或文件夹
* @param filePath:目标文件名(完整路径)
* @throws IOException
* @return boolean
*/
public static boolean createFile(String filePath) throws IOException {
if (filePath == null || "".equals(filePath.trim())) {
throw new IOException("filePath is " + null + " or null String");
}
if (filePath.indexOf("/") != -1 && filePath.indexOf("\\") != -1) {
throw new IOException("The filePath " + filePath + " is "
+ " invalid");
}
File file = new File(filePath);
boolean isDirectory = false;
// 判断是否文件夹,若是文件夹则创建后返回
if (filePath.lastIndexOf("/") == filePath.length() - 1
|| filePath.lastIndexOf("\\") == filePath.length() - 1) {
isDirectory = true;
}
if (isDirectory) {// 是文件夹
if (file.isDirectory()) {// 若已存在,则无需创建,直接返回
return true;
} else {// 若不存在,则创建
return createMkdirsOrFiles(filePath, 1);
}
} else {// 是文件
if (file.isFile()) {// 若文件存在,则先删除,在创建,再返回
boolean fd = file.delete();
if (fd)
return file.createNewFile();
else
return true;// 是否应该返回true,因为目标文件可能是删除不掉的原来的文件
} else {// 若文件不存在,先创建,再返回
return createMkdirsOrFiles(filePath, 2);
}
}
}
/**
* @Title:createMkdirsOrFiles
* @description:创建文件夹或文件(目标文件或文件夹不存在)
* @param filePath
* @param type:1-文件夹 2-文件
* @return boolean
* @throws IOException
*/
private static boolean createMkdirsOrFiles(String filePath, int type) throws IOException {
// boolean res = false ;
File file = new File(filePath);
if (type == 1) {
if (file.isDirectory())
return true;
file.mkdirs();
return file.isDirectory();
} else if (type == 2) {
int index1 = file.getPath().indexOf(File.separator);
if (index1 != -1) {
int index2 = file.getPath().indexOf(File.separator, index1 + 1);
if (index2 != -1) {
int indexLast = file.getPath().lastIndexOf(File.separator);
String dir = filePath.substring(0, indexLast + 1);
File f = new File(dir);
if (!f.isDirectory()) {
f.mkdirs();
boolean res = f.isDirectory();
if (res) {
file.createNewFile();
return file.exists();
} else {
return false;
}
} else {
file.createNewFile();
return file.exists();
}
} else {
file.createNewFile();
return file.exists();
}
}else{
throw new IOException("The filePath:" + filePath + " separator is " + " invalid");
}
} else
return false;
}
}