文件操作工具类

文件操作工具类

删除文件及子文件,当 includeSelfDir=true,删除文件夹自身(见代码样例)

文件重命名(见代码样例)

文件复制(见代码样例)

文件更换目录(见代码样例)

新建文件(见代码样例)

新建一级目录(见代码样例)

新建多级目录(见代码样例)

获取所有文件名-是否包含子文件(见代码样例)

获取所有文件绝对路径-是否包含子文件(见代码样例)

获取所有文件绝对路径-是否包含子文件(见代码样例)

代码样例

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.List;
import java.util.Objects;

import com.google.common.collect.Lists;
import lombok.experimental.UtilityClass;
import org.apache.commons.collections4.ListUtils;
import org.junit.platform.commons.util.Preconditions;
import org.junit.platform.commons.util.StringUtils;

/**
 * @Title:文件操作工具类
 * @Description:
 * @Copyright: Copyright(c)2022
 * @Company: bestcxx
 * @Author: wujie
 * @Date:2022-12-04
 * @Updatedby:
 */
@UtilityClass
public class FileUtils {

    public static void main(String[] args) throws IOException {


        String path2 = "/Users/aaa/Desktop/mkdirtest";
        String path3 = "/Users/aaa/Desktop/mkdirtest2/sub";
        mkdir(path2);
        mkdir(path3);
        String path4 = "/Users/aaa/Desktop/mkdirtest/sub1/";
        String path5 = "/Users/aaa/Desktop/mkdirtest/sub2/sub21/sub31";
        mkdirs(path4);
        mkdirs(path5);

        System.out.println(getDerictFileNameByPath(path3));
        System.out.println(getAllFileNameByPath(path3));
        System.out.println(createFile(path4 + "/sub1/", "b.word"));
        System.out.println(moveFile(path4 + "/sub1/b.word", path4 + "/sub1/g.word"));
        System.out.println(copyFile(path4 + "/sub1/g.word", path4 + "/sub1/h.word"));
        System.out.println(renameFile(path4 + "/sub1/h.word", path4 + "/sub1/h2.word"));
        String path6 = "/Users/aaa/Desktop/mkdirtest";
        System.out.println(deleteFileOrAllSubFile(path6,true));

    }

    /**
     * 删除文件及子文件,当 includeSelfDir=true,删除文件夹自身
     *
     * @param originPath 根文件夹
     * @param file
     * @return
     * @throws IOException
     */
    private boolean deleteFileOrSubFile(String originPath,File file,boolean includeSelfDir) throws IOException {
        // 待删除目录不能以 / 结尾
        Preconditions.condition(originPath.lastIndexOf("/")+1 != originPath.length(),"待删除目录结尾不能以 / 结尾");

        if (file.isFile()) {
            String tem = file.getAbsolutePath();
            if(file.delete()){
                System.out.println(String.format("%s 被删除",tem));
            }
        } else if (file.isDirectory()) {
            for (File subFile : file.listFiles()) {
                deleteFileOrSubFile(originPath,subFile,includeSelfDir);
            }
            String tem = file.getAbsolutePath();
            if(originPath.equals(tem)){
                if(includeSelfDir && file.delete()){
                    System.out.println(String.format("%s 入参根目录被删除",tem));
                }
            }else if(file.delete()){
                System.out.println(String.format("%s 被删除",tem));
            }
        }
        return true;
    }

    /**
     * 删除文件及子文件,当 includeSelfDir=true,删除文件夹自身
     *
     * @param fullPath
     * @return
     * @throws IOException
     */
    public boolean deleteFileOrAllSubFile(String fullPath,boolean includeSelfDir) throws IOException {
        return deleteFileOrSubFile(fullPath,new File(fullPath),includeSelfDir);
    }

    public boolean renameFile(String fullPathFrom, String fullPathTarget) throws IOException {
        File fileFrom = new File(fullPathFrom);
        File fileTarget = new File(fullPathTarget);
        return fileFrom.renameTo(fileTarget);
    }

    public boolean copyFile(String fullPathFrom, String fullPathTarget) throws IOException {
        File fileFrom = new File(fullPathFrom);
        File fileTarget = new File(fullPathTarget);
        Files.copy(fileFrom.toPath(), fileTarget.toPath(), StandardCopyOption.REPLACE_EXISTING);
        return true;
    }

    public boolean moveFile(String fullPathFrom, String fullPathTarget) throws IOException {
        File fileFrom = new File(fullPathFrom);
        File fileTarget = new File(fullPathTarget);
        Files.move(fileFrom.toPath(), fileTarget.toPath(), StandardCopyOption.REPLACE_EXISTING);
        return true;
    }

    public boolean createFile(String prePath, String fileName) throws IOException {
        String targatFilePath = prePath + fileName;
        File targetFile = new File(targatFilePath);
        if (targetFile.isFile()) {
            System.out.println(String.format("%s 目标文件已存在 ", targatFilePath));
            return true;
        }

        File parentPath = new File(prePath);
        if (parentPath.isDirectory()) {
            System.out.println(String.format("%s 层级目录结构已存在 ", prePath));
        } else {
            System.out.println(String.format("层级目录结构初始化 %s ", prePath));
            mkdirs(prePath);
        }
        new FileWriter(prePath + fileName).close();
        System.out.println(String.format("目标文件初始化 %s", targatFilePath));

        return true;
    }

    /**
     * 新建单级目录
     *
     * @param path
     * @return
     */
    public boolean mkdir(String path) {
        File file = new File(path);
        if (StringUtils.isNotBlank(file.getParent())) {
            return file.mkdir();
        }
        return false;
    }

    /**
     * 新建多级目录
     *
     * @param path
     * @return
     */
    public boolean mkdirs(String path) {
        File file = new File(path);
        return file.mkdirs();
    }

    public List<String> getDerictFileNameByPath(String path) {
        File file = new File(path);
        if (!file.exists()) {
            return Lists.newArrayList();
        }
        return getFileNames(file, Lists.newArrayList(), true);

    }

    public List<String> getAllFileNameByPath(String path) {
        File file = new File(path);
        if (!file.exists()) {
            return Lists.newArrayList();
        }
        return getFileNames(file, Lists.newArrayList(), false);

    }

    public List<String> getAbsoluteFileNameByPath(String path) {
        File file = new File(path);
        if (!file.exists()) {
            return Lists.newArrayList();
        }
        return getAbsoluteFileName(file, Lists.newArrayList(), false);

    }

    public List<File> getAllFilesByPath(String path) {
        File file = new File(path);
        if (!file.exists()) {
            return Lists.newArrayList();
        }
        return getAllFiles(file, Lists.newArrayList(), false);

    }

    /**
     * 默认不返回 隐藏文件
     *
     * @param file
     * @param fileNames
     * @param onlyDerictFile
     * @return
     */
    public List<String> getFileNames(File file, List<String> fileNames, boolean onlyDerictFile) {
        if (Objects.isNull(file)) {
            return ListUtils.emptyIfNull(fileNames);
        }
        File[] files = file.listFiles();
        for (File f : files) {
            if (f.isDirectory() && !onlyDerictFile) {
                getFileNames(f, fileNames, onlyDerictFile);
            } else if (f.isFile() && !f.isHidden()) {
                //不要隐藏文件
                fileNames.add(f.getName());
            }
        }
        return fileNames;
    }

    /**
     * 默认不返回 隐藏文件
     *
     * @param file
     * @param allFiles
     * @param onlyDerictFile
     * @return
     */
    public List<String> getAbsoluteFileName(File file, List<String> allFiles, boolean onlyDerictFile) {
        if (Objects.isNull(file)) {
            return ListUtils.emptyIfNull(allFiles);
        }
        File[] files = file.listFiles();
        for (File f : files) {
            if (f.isDirectory() && !onlyDerictFile) {
                getAbsoluteFileName(f, allFiles, onlyDerictFile);
            } else if (f.isFile() && !f.isHidden()) {
                //不要隐藏文件
                allFiles.add(f.getAbsolutePath());
            }
        }
        return allFiles;
    }

    /**
     * 默认不返回 隐藏文件
     *
     * @param file
     * @param allFiles
     * @param onlyDerictFile
     * @return
     */
    public List<File> getAllFiles(File file, List<File> allFiles, boolean onlyDerictFile) {
        if (Objects.isNull(file)) {
            return ListUtils.emptyIfNull(allFiles);
        }
        File[] files = file.listFiles();
        for (File f : files) {
            if (f.isDirectory() && !onlyDerictFile) {
                getAllFiles(f, allFiles, onlyDerictFile);
            } else if (f.isFile() && !f.isHidden()) {
                //不要隐藏文件
                allFiles.add(f);
            }
        }
        return allFiles;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值