铁马冰河2000

导航

统计

文件工具类-FileUtil

功能介绍
1.文件或者目录重命名
2.文件拷贝操作
3.创建文件
4.创建文件目录
5.将文件名称排序
6.将文件名称排序
7.将文件大小排序
8.删除文件或者目录下文件(包括目录)

==============================================文件工具类

复制代码
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FileUtil {
    
    private static final Logger logger = LoggerFactory.getLogger(FileUtil.class);
    
    /**
     * 文件或者目录重命名
     * @param oldFilePath 旧文件路径
     * @param newName 新的文件名,可以是单个文件名和绝对路径
     * @return
     */
    public static boolean renameTo(String oldFilePath, String newName) {
        try {
            File oldFile = new File(oldFilePath);
            //若文件存在
            if(oldFile.exists()){
                //判断是全路径还是文件名
                if (newName.indexOf("/") < 0 && newName.indexOf("\\") < 0){
                    //单文件名,判断是windows还是Linux系统
                    String absolutePath = oldFile.getAbsolutePath();
                    if(newName.indexOf("/") > 0){
                        //Linux系统
                        newName = absolutePath.substring(0, absolutePath.lastIndexOf("/") + 1)  + newName;
                    }else{
                        newName = absolutePath.substring(0, absolutePath.lastIndexOf("\\") + 1)  + newName;
                    }
                }
                File file = new File(newName);
                //判断重命名后的文件是否存在
                if(file.exists()){
                    logger.info("该文件已存在,不能重命名 newFilePath={}", file.getAbsolutePath());
                }else{
                    //不存在,重命名
                    return oldFile.renameTo(file);
                }
            }else {
                logger.info("原该文件不存在,不能重命名 oldFilePath={}", oldFilePath);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
    
    /**
     * 文件拷贝操作
     * @param sourceFile
     * @param targetFile
     *     若目标文件目录不存在,也会自动创建
     */
    public static void copy(String sourceFile, String targetFile) {
        File source = new File(sourceFile);
        File target = new File(targetFile);
        target.getParentFile().mkdirs();
        FileInputStream fis = null;
        FileOutputStream fos = null;
        FileChannel in = null;
        FileChannel out = null;
        try {
            fis = new FileInputStream(source);
            fos = new FileOutputStream(target);
            in = fis.getChannel();//得到对应的文件通道
            out = fos.getChannel();//得到对应的文件通道
            in.transferTo(0, in.size(), out);//连接两个通道,并且从in通道读取,然后写入out通道
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null){
                    out.close();
                }
                if (in != null){
                    in.close();
                }
                if (fos != null){
                    fos.close();
                }
                if (fis != null){
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    /**
     * 创建文件
     * @param filePath
     * @return
     */
    public static File mkFile(String filePath) {
        File file = new File(filePath);
        if(!file.exists()) {
            String dirPath = FilePathUtil.extractDirPath(filePath);
            if(mkdirs(dirPath)) {
                try {
                    file.createNewFile();
                    logger.info("文件创建成功. filePath={}", filePath);
                    return file;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }else {
                logger.info("文件目录创建失败. dirPath={}", dirPath);
            }
        }else {
            logger.info("文件已存在,无需创建. filePath={}", filePath);
        }
        return null;
    }
    
    /**
     * 创建文件目录
     * @param dirPath
     * @return
     */
    public static boolean mkdirs(String dirPath) {
        try{
            File fileDir = new File(dirPath);
            if(!fileDir.exists()){
                fileDir.mkdirs();
                logger.info("文件目录创建成功. dirPath={}", dirPath);
            }else {
                logger.info("文件目录已存在,无需创建. dirPath={}", dirPath);
            }
            return true;
        }catch(Exception e){
            e.printStackTrace();
        }
        return false;
    }
    
    /**
     * 将文件名称排序
     * @param filePath
     * @return
     */
    public static List<File> sortByName(String filePath){
        File[] files = new File(filePath).listFiles();
        List<File> fileList = Arrays.asList(files);
        Collections.sort(fileList, new Comparator<File>() {
            public int compare(File o1, File o2) {
                if (o1.isDirectory() && o2.isFile())
                    return -1;
                if (o1.isFile() && o2.isDirectory())
                    return 1;
                return o1.getName().compareTo(o2.getName());
            }
        });
        return fileList;
    }
    
    /**
     * 将文件修改日期排序
     * @param filePath
     * @return
     */
    public static List<File> sortByDate(String filePath){
        File[] files = new File(filePath).listFiles();
        List<File> fileList = Arrays.asList(files);
        Collections.sort(fileList, new Comparator<File>() {
            public int compare(File f1, File f2) {
                long diff = f1.lastModified() - f2.lastModified();
                if (diff > 0)
                    return 1;
                else if (diff == 0)
                    return 0;
                else
                    return -1;//如果 if 中修改为 返回-1 同时此处修改为返回 1  排序就会是递减
            }
        });
        return fileList;
    }
    
    /**
     * 将文件大小排序
     * @param filePath
     * @return
     */
    public static List<File> sortByLength(String filePath){
        File[] files = new File(filePath).listFiles();
        List<File> fileList = Arrays.asList(files);
        Collections.sort(fileList, new Comparator<File>() {
            public int compare(File f1, File f2) {
                long diff = f1.length() - f2.length();
                if (diff > 0)
                    return 1;
                else if (diff == 0)
                    return 0;
                else
                    return -1;//如果 if 中修改为 返回-1 同时此处修改为返回 1  排序就会是递减
            }
        });
        return fileList;
    }
    
    /**
     * 删除文件或者目录下文件(包括目录)
     * @param filePath
     * @return
     */
    public static boolean delete (String filePath){
        try{
            File sourceFile = new File(filePath);
            if(sourceFile.isDirectory()){
                for (File listFile : sourceFile.listFiles()) {
                    delete(listFile.getAbsolutePath());
                }
            }
            return sourceFile.delete();
        }catch(Exception e){
            e.printStackTrace();
        }
        return false;
    }
}
复制代码

 

==============================================文件工具测试类

复制代码
    /**
     * 文件或者目录重命名
     */
    @Test
    public void test_fileRename() {
        String oldFilePath = "E:/home/commUtils/temp/Person04";
        String newName = "E:/home/commUtils/temp/Person03";
        boolean renameTo = FileUtil.renameTo(oldFilePath, newName);
        System.out.println(renameTo);
    }
    
    /**
     * 文件拷贝
     */
    @Test
    public void test_fileCopy() {
        String sourceFile = "E:/home/commUtils/temp/person/Person05.txt";
        String targetFile = "E:/home/commUtils/temp/person04/Person04.txt";
        FileUtil.copy(sourceFile, targetFile);
    }
    
    /**
     * 文件创建
     */
    @Test
    public void test_fileCreate() {
        // 可以连续创建 temp person目录
//        String dirPath = "E:/home/commUtils/temp/person";
//        boolean mkdirs = FileUtil.mkdirs(dirPath);
//        System.out.println(mkdirs);
        
        String filePath = "E:/home/commUtils/temp/person/Person05.txt";
        File mkFile = FileUtil.mkFile(filePath);
        System.out.println(mkFile.getName());
    }
    
    /**
     * 文件排序
     */
    @Test
    public void test_fileSort() {
        String filePath = "E:\\home\\commUtils\\temp";
//        List<File> fileList = FileUtil.sortByLength(filePath);
//        List<File> fileList = FileUtil.sortByDate(filePath);
        List<File> fileList = FileUtil.sortByName(filePath);
        for(File file : fileList) {
            System.out.println(file.getName());
        }
    }
    
    /**
     * 删除文件或者目录下文件(包括目录)
     */
    @Test
    public void test_delete() {
        String filePath = "E:\\home\\commUtils\\temp\\Person.txt";
        boolean delete = FileUtil.delete(filePath);
        System.out.println(delete);
    }
复制代码

 

posted on   铁马冰河2000  阅读(1894)  评论(1编辑  收藏  举报

相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示