package com.zzy.tools;
import java.io.File;
import java.io.IOException;
import com.iodemo.Const;
/**
* 文件的工具类,自动根据字符串来创建文件或者文件夹
*
* @author zzy
*/
public class FileTool {
/**
* 根据路径来自己创建是文件还是文件夹
*
* @param path
* @return
*/
private static boolean createFile(String path) {
if (path.contains(".")) {
int partition1 = path.lastIndexOf("/");
if (partition1 == -1) {
partition1 = path.lastIndexOf("\\");
}
// 纯文件名
String fileName = path.substring(partition1 + 1);
String filePath = path.substring(0, partition1);
return createNewFile(fileName, filePath);
} else {
return createCatalog(path);
}
}
/**
* 创建文件
*
* @param fileName
* @param filePath
* @return
*/
private static boolean createNewFile(String fileName, String filePath) {
if (createCatalog(filePath)) {
File f = new File(filePath, fileName);
try {
return f.createNewFile();
} catch (IOException e) {
new RuntimeException("创建文件失败");
e.printStackTrace();
}
}
return false;
}
/**
* 根据目录路径创建目录
*
* @param
* @return
*/
private static boolean createCatalog(String path) {
File f = new File(path);
if (!f.exists()) {
return f.mkdirs();
}
return true;
}
public static void main(String[] args) {
// "/Volumes/d/ioTest/fdafdafdasfdsafdsa/1.txt"
String path = Const.WRITE_PATH;
path = "jfiodasjfpo";
if (createFile(path)) {
System.out.println("创建成功");
} else {
System.out.println("创建失败");
}
}
}
文件工具类——根据路径自己创建文件或者文件夹
最新推荐文章于 2024-07-31 04:35:37 发布