- import org.apache.commons.io.FileUtils;
- import org.apache.commons.logging.Log;
- import org.apache.commons.logging.LogFactory;
- import java.io.File;
- import java.io.IOException;
- /**
- * 文件工具箱
- *
- * @author
- */
- public final class FileTookit {
- private static final Log log = LogFactory.getLog(FileTookit.class);
- /**
- * 复制文件或者目录,复制前后文件完全一样。
- *
- * @param resFilePath 源文件路径
- * @param distFolder 目标文件夹
- * @IOException 当操作发生异常时抛出
- */
- public static void copyFile(String resFilePath, String distFolder) throws IOException {
- File resFile = new File(resFilePath);
- File distFile = new File(distFolder);
- if (resFile.isDirectory()) {
- FileUtils.copyDirectoryToDirectory(resFile, distFile);
- } else if (resFile.isFile()) {
- FileUtils.copyFileToDirectory(resFile, distFile, true);
- }
- }
- /**
- * 删除一个文件或者目录
- *
- * @param targetPath 文件或者目录路径
- * @IOException 当操作发生异常时抛出
- */
- public static void deleteFile(String targetPath) throws IOException {
- File targetFile = new File(targetPath);
- if (targetFile.isDirectory()) {
- FileUtils.deleteDirectory(targetFile);
- } else if (targetFile.isFile()) {
- targetFile.delete();
- }
- }
- /**
- * 移动文件或者目录,移动前后文件完全一样,如果目标文件夹不存在则创建。
- *
- * @param resFilePath 源文件路径
- * @param distFolder 目标文件夹
- * @IOException 当操作发生异常时抛出
- */
- public static void moveFile(String resFilePath, String distFolder) throws IOException {
- File resFile = new File(resFilePath);
- File distFile = new File(distFolder);
- if (resFile.isDirectory()) {
- FileUtils.moveDirectoryToDirectory(resFile, distFile, true);
- } else if (resFile.isFile()) {
- FileUtils.moveFileToDirectory(resFile, distFile, true);
- }
- }
- /**
- * 重命名文件或文件夹
- *
- * @param resFilePath 源文件路径
- * @param newFileName 重命名
- * @return 操作成功标识
- */
- public static boolean renameFile(String resFilePath, String newFileName) {
- String parentFilePath = new File(resFilePath).getParent();
- String newFilePath = StringTookit.formatPath(parentFilePath + "/" + newFileName);
- File resFile = new File(resFilePath);
- File newFile = new File(newFilePath);
- return resFile.renameTo(newFile);
- }
- /**
- * 读取文件或者目录的大小
- *
- * @param distFilePath 目标文件或者文件夹
- * @return 文件或者目录的大小,如果获取失败,则返回-1
- */
- public static Long genFileSize(String distFilePath) {
- File distFile = new File(distFilePath);
- if (distFile.isFile()) {
- return distFile.length();
- } else if (distFile.isDirectory()) {
- return FileUtils.sizeOfDirectory(distFile);
- }
- return -1L;
- }
- }
Java文件操作
最新推荐文章于 2024-07-16 22:44:27 发布