import java.io.File;
import java.io.IOException;
public class CreateFile {
/**
*
* @param path 文件夹路径
* @return
*/
public static void createFile(String path){
String str = spiltFilePath(path);
File file = new File(str);
File file1 = new File(path);
if(file.exists()){
System.out.println("该文件夹已经存在");
}else if(path.equals(str)){
//相同的话只创建文件夹
file.mkdirs();
}else{
//不相同则创建文件夹及文件
file.mkdirs();//新建一个文件夹
try {
file1.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
*
* @param path 文件夹路径
* @return 返回一个String类型的路径
*/
public static String spiltFilePath(String path) {
boolean flag = path.contains(".");//判断要创建的是文件还是文件夹
if (flag) {
String[] str = path.split("\\//");//按照"//"切割文件路径
String parentpath = str[0];
for (int i = 0; i < str.length - 1; i++) {
if ((i + 1) != str.length - 1) {
parentpath += "//" + str[i + 1];
}
}
return parentpath;
} else {
return path;
}
}
public static void main(String[] args) {
createFile("E://ccc//ccc//c");//测试数据
}
}
创建文件夹及文档(多层)
最新推荐文章于 2020-12-05 01:48:20 发布