FileUtil工具类

news2024/9/24 15:17:12
  • 【版权所有,文章允许转载,但须以链接方式注明源地址,否则追究法律责任】
  • 【创作不易,点个赞就是对我最大的支持】

前言

仅作为学习笔记,供大家参考
总结的不错的话,记得点赞收藏关注哦!

目录

    • 前言
    • 1、文件基本操作工具类 ->创建、复制、删除、文件名称修改
    • 2、文件、文件夹压缩
    • 3、文件下载
    • 4、word文档转pdf
    • 5、文件预览
    • 6、Base64文件流、文件二进制字符串转文件
    • 7、压缩包解压

1、文件基本操作工具类 ->创建、复制、删除、文件名称修改

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import java.io.*;
import java.nio.channels.FileChannel;
import java.util.HashSet;
import java.util.Set;

/**
 * File文件、文件夹的基本操作, 创建、复制、删除、文件名称修改、文件下载
 */
public class FileUtils {

    /**
     * nio写文件
     * @param fileName
     * @param content
     * @return
     */
    public static void writeFile(String fileName, String content) {
        //获取通道
        FileOutputStream fos = null;
        FileChannel channel = null;
        ByteBuffer buffer = null;
        try {
            fos = new FileOutputStream(fileName);
            channel = fos.getChannel();
            buffer = ByteBuffer.wrap(content.getBytes());
            //将内容写到缓冲区
            fos.flush();
            channel.write(buffer);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            log.error(fileName+"文件不存在", e);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("IO异常", e);
        } finally {
            try {
                if (channel != null) {
                    channel.close();
                }
            } catch (IOException ee) {
                log.error("IO异常", ee);
            }
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException ee) {
                log.error("IO异常", ee);
            }
        }
    }
    /**
     * 读取文件
     * @param fileName
     * @return
     */
    public static String readFile(String fileName) {
        String str = null;
        //获取通道
        FileInputStream fis = null;
        FileChannel channel = null;
        try {
            fis = new FileInputStream(fileName);
            channel = fis.getChannel();
            //指定缓冲区
            ByteBuffer buf = ByteBuffer.allocate(1024);
            //将通道中的数据读到缓冲区中
            channel.read(buf);
            byte[] arr = buf.array();
            str = new String(arr);
        } catch (FileNotFoundException e) {
            log.error(fileName+"文件不存在", e);
        } catch (IOException e) {
            log.error("IO异常", e);
        } finally {
            try {
                if (channel != null) {
                    channel.close();
                }
            } catch (IOException ee) {
                log.error("IO异常", ee);
            }
            try {
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException ee) {
                ee.printStackTrace();
                log.error("IO异常", ee);
            }
        }
        return str.toString();
    }
    
    /**
     * 如果目录不存在,就创建文件
     * @param dirPath
     * @return
     */
    public static String mkdirs(String dirPath) {
        try{
            File file = new File(dirPath);
            if(!file.exists()){
                file.mkdirs();
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return dirPath;
    }

    /**
     * 判断文件是否存在
     * @param filePath 文件路径
     * @return
     */
    public static boolean isExists(String filePath) {
        File file = new File(filePath);
        return file.exists();
    }

    /**
     * 判断是否是文件夹
     * @param path
     * @return
     */
    public static boolean isDir(String path) {
        File file = new File(path);
        if(file.exists()){
            return file.isDirectory();
        }else{
            return false;
        }
    }


    /**
     * 删除空目录
     * @param dir 将要删除的目录路径
     */
    private static void doDeleteEmptyDir(String dir) {
        boolean success = (new File(dir)).delete();
        if (success) {

        } else {

        }
    }

    /**
     * 递归删除目录下的所有文件及子目录下所有文件
     * @param dir 将要删除的文件目录
     * @return boolean Returns "true" if all deletions were successful.
     *                 If a deletion fails, the method stops attempting to
     *                 delete and returns "false".
     */
    public static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            //递归删除目录中的子目录下
            for (int i=0; i<children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        // 目录此时为空,可以删除
        return dir.delete();
    }

    /**
     * @Title: deleteFile
     * @Description: 除文件夹中指定的文件类型,如果有文件夹则不删除文件夹中的文件
     * @param path
     * @param fileType
     */
    public static void deleteFile(String path, String fileType){
        if(StringUtils.isNullOrBlank(path)){
            return;
        }
        File file = new File(path);
        if(file.isFile()){//文件
            File[] listFiles = {file};
            deleteFileByType(listFiles, fileType);
        }
        if(file.isDirectory()){//文件夹
            File[] listFiles = file.listFiles();
            deleteFileByType(listFiles, fileType);
        }
    }

    /**
     * @Title: cycleDeleteFile
     * @Description: 循环删除文件夹中指定的文件类型
     * @param path
     * @param fileType
     */
    public static void cycleDeleteFile(String path, String fileType){
        if(StringUtils.isNullOrBlank(path)){
            return;
        }
        File file = new File(path);
        if(file.isFile()){//文件
            File[] listFiles = {file};
            deleteFileByType(listFiles, fileType);
        }
        if(file.isDirectory()){//文件夹
            String[] files = file.list();
            for(String filePath : files){
                cycleDeleteFile(file.getPath() + File.separator + filePath, fileType);
            }
        }
    }

    /**
     * @Title: deleteFileByType
     * @Description: 判断文件是否是指定的类型,如果是则删除之
     * @param listFiles
     * @param fileType
     */
    public static void deleteFileByType(File[] listFiles, String fileType) {
        if(listFiles == null || listFiles.length <= 0){
            return;
        }
        String suffixName = "";
        for(File file : listFiles){
            if(!file.isFile()){//文件
                continue;
            }
            suffixName = getSuffixName(file);
            if(StringUtils.isNullOrBlank(suffixName)){
                continue;
            }
            if(fileType.equals(suffixName)){
                if(!file.delete()){
                    log.error("删除" + file.getPath() + "失败");
                }
            }
        }
    }
 /**
     * 删除文件,可以是单个文件或文件夹
     *
     * @param fileName
     *            待删除的文件名
     * @return 文件删除成功返回true,否则返回false
     */
    public static boolean delete(String fileName) {
        File file = new File(fileName);

        if (!file.exists()) {
            System.out.println("删除文件失败:" + fileName + "文件不存在");
            return false;
        } else {
            if (file.isFile()) {

                return deleteFile(fileName);
            } else {
                return deleteDirectory(fileName);
            }
        }
    }

    /**
     * 删除单个文件
     *
     * @param fileName
     *            被删除文件的文件名
     * @return 单个文件删除成功返回true,否则返回false
     */
    public static boolean deleteFile(String fileName) {
        File file = new File(fileName);

        if (file.isFile() && file.exists()) {
            file.delete();
            System.out.println("删除单个文件" + fileName + "成功!");
            return true;
        } else {
            System.out.println("删除单个文件" + fileName + "失败!");
            return false;
        }
    }

    /**
     * 删除目录(文件夹)以及目录下的文件
     *
     * @param dir
     *            被删除目录的文件路径
     * @return 目录删除成功返回true,否则返回false
     */
    public static boolean deleteDirectory(String dir) {
        // 如果dir不以文件分隔符结尾,自动添加文件分隔符
        if (!dir.endsWith(File.separator)) {
            dir = dir + File.separator;
        }
        File dirFile = new File(dir);
        // 如果dir对应的文件不存在,或者不是一个目录,则退出
        if (!dirFile.exists() || !dirFile.isDirectory()) {
            System.out.println("删除目录失败" + dir + "目录不存在!");
            return false;
        }
        boolean flag = true;
        // 删除文件夹下的所有文件(包括子目录)
        File[] files = dirFile.listFiles();
        for (int i = 0; i < files.length; i++) {
            // 删除子文件
            if (files[i].isFile()) {
                flag = deleteFile(files[i].getAbsolutePath());
                if (!flag) {
                    break;
                }
            }
            // 删除子目录
            else {
                flag = deleteDirectory(files[i].getAbsolutePath()); // 如果目录下还有目录,这反复调用
                // deleteDirectory
                if (!flag) {
                    break;
                }
            }
        }

        if (!flag) {
            System.out.println("删除目录失败");
            return false;
        }

        // 删除当前目录
        if (dirFile.delete()) {
            System.out.println("删除目录" + dir + "成功!");
            return true;
        } else {
            System.out.println("删除目录" + dir + "失败!");
            return false;
        }
    }
    /**
     * @Title: getSuffixName
     * @Description: 返回文件的后缀名, 如JPEG:FFD8FF
     * @param file
     * @return
     */
    public static String getSuffixName(File file){
        if(!file.isFile()){
            return null;
        }
        FileInputStream is = null;
        byte[] src = new byte[3];
        StringBuilder sBuilder = null;
        String hv = null;
        try {
            is = new FileInputStream(file);
            src = new byte[3];
            is.read(src, 0, src.length);
            is.close();
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        if (src == null || src.length <= 0) {
            return null;
        }
        sBuilder = new StringBuilder();
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                sBuilder.append(0);
            }
            sBuilder.append(hv);
        }
        if(sBuilder.length() <= 0){
            return null;
        }
        return sBuilder.toString().toUpperCase();
    }



    /**
     * File 文件或者目录重命名
     * @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()){
                    System.out.println("该文件已存在,不能重命名");
                }else{
                    //不存在,重命名
                    return oldFile.renameTo(file);
                }
            }else {
                System.out.println("原该文件不存在,不能重命名");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 文件复制
     * @param src 要复制
     * @param des  复制到
     * @return
     */

    public static boolean copyDir(String src, String des)  {
        try {
            //初始化文件复制
            File file1=new File(src);
            if(!file1.exists()){
                return false;
            }else{
                //把文件里面内容放进数组
                File[] fs=file1.listFiles();
                //初始化文件粘贴
                File file2=new File(des);
                //判断是否有这个文件有不管没有创建
                if(!file2.exists()){
                    file2.mkdirs();
                }
                //遍历文件及文件夹
                for (File f : fs) {
                    if(f.isFile()){
                        //文件
                        fileCopy(f.getPath(),des+ File.separator+f.getName()); //调用文件拷贝的方法
                    }else if(f.isDirectory()){
                        //文件夹
                        copyDir(f.getPath(),des+File.separator+f.getName());//继续调用复制方法      递归的地方,自己调用自己的方法,就可以复制文件夹的文件夹了
                    }
                }
                return true;
            }
        }catch (Exception e){
            e.getStackTrace();
            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 previousDir 上一层目录
     * @param dirName 当前目录名
     * @return
     */
    public static String getSaveDir(String previousDir, String dirName) {
        if (StringUtils.isNotBlank(previousDir)){
            dirName = previousDir + "/" + dirName + "/";
        }else {
            dirName = dirName + "/";
        }
        return dirName;
    }



    //其他方法
    public static Set<String> getDirName(String fName){
        Set<String> set = new HashSet<>();
        String fileName = null;
        File tempFile =new File( fName.trim());
        if(tempFile.exists()){
            File[] array = tempFile.listFiles();
            for(int i = 0 ; i<array.length ; i++){
                set.add(array[i].getName().toString());
            }
        }
        System.out.println(set);
        return set;
    }

    /**
     * 文件复制的具体方法
     */
    private static void fileCopy(String src, String des) throws Exception {
        //io流固定格式
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(src));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(des));
        int i = -1;//记录获取长度
        byte[] bt = new byte[2014];//缓冲区
        while ((i = bis.read(bt))!=-1) {
            bos.write(bt, 0, i);
        }
        bis.close();
        bos.close();
        //关闭流
    }

    public static String getFileName(String fName){
        String fileName = null;
        File tempFile =new File( fName.trim());
        if(tempFile.exists()){
            File[] array = tempFile.listFiles();
            for(int i = 0 ; i<array.length ; i++){
                String houzhui = array[i].toString().substring(array[i].toString().lastIndexOf(".") + 1);
                if(houzhui.equals("iw")||houzhui.equals(".zip")){
                    fileName = array[i].getName();
                }
            }
        }
        return fileName;
    }


}

2、文件、文件夹压缩

文件、文件夹压缩

3、文件下载

文件下载

4、word文档转pdf

word文档转pdf

5、文件预览

文件预览

6、Base64文件流、文件二进制字符串转文件

Base64文件流、文件二进制字符串转文件

7、压缩包解压

压缩包解压

创作不易,点个赞就是对我最大的支持~


公众号:程序员温眉

在这里插入图片描述
CSDN:程序员温眉

每天进步一点点的程序员

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1285200.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

8.7 矢量图层点要素点分布(Point displacement)使用

文章目录 前言点分布&#xff08;Point displacement&#xff09;QGis代码实现 总结 前言 前面介绍了矢量-点要素-单一符号、矢量-点要素-分类符号、矢量-点要素-分级符号以及矢量-点要素-基于规则的使用本章介绍如何使用点分布&#xff08;Point displacement&#xff09;说明…

12、pytest上下文友好的输出

官方实例 # content of test_assert2.py import pytestdef test_set_comparison():set1 set("1308")set2 set("8035")assert set1 set2def test_dict_comparison():dict_1 {name:陈畅,sex:男}dict_2 {name:赵宁,sex:女}assert dict_1 dict_2def tes…

19、pytest通过mark标记测试函数

官方实例 [pytest] markers slow:marks tests as slow(deselect with -m "not slow")serial# content of test_mark.py import pytestpytest.mark.slow def test_mark_function():print("test_mark_function was invoked")assert 0解读与实操 通过使用p…

netcore swagger 错误 Failed to load API definition

后端接口报错如下&#xff1a; 前端nswag报错如下&#xff1a; 根据网上查询到的资料说明&#xff0c;说一般swagger这种错误都是控制器里有接口代码异常造成的&#xff0c;通常是接口没有加属性Attribute&#xff0c; 比如[HttpPost("Delete")]、[HttpGet("Del…

failed to install plugin grafana 插件安装失败

升级时忽略plugins 权限问题&#xff0c;导致安装插件失败&#xff01;调整权限即可

你知道和不知道的微信小游戏常用API整理,赶紧收藏用起来~

引言 这…已收藏 最近在书院(一个提供优质内容&#xff0c;专门搞学习的地方,可私信“星球”了解和捧场)看到比较多的星友想学习Cocos进行小游戏开发。 “该从什么方向入手&#xff1f;” 从星友们的主题可以看出&#xff0c;小游戏目前不管是国内还是海外&#xff0c;都非常…

Node 后端 框架 Nest js鉴权

使用 nest g res auth去生成restful风格的auth模块&#xff0c;下面是具体操作 nest g res auth安装基础依赖 {"name": "auth","version": "0.0.1","description": "","author": "","…

第四节 数组

第四节 数组 目录 一&#xff0e; 一维数组的创建和初始化1. 一维数组的创建2. 数组的初始化3. 一维数组的使用4. 一维数组在内存中的存储 二&#xff0e; 二维数组的创建和初始化1. 二维数组的创建2. 二维数组的初始化3. 二维数组的使用4. 二维数组在内存中的存储 三&#xff…

梯度上升和随机梯度上升

目录 梯度上升算法&#xff1a; 代码&#xff1a; 随机梯度上升算法&#xff1a; 代码&#xff1a; 实验&#xff1a; 做图代码&#xff1a; 疑问&#xff1a; 1.梯度上升算法不适应大的数据集&#xff0c;改用随机梯度上升更合适。 2.改进过的随机梯度算法&#xff0…

1.nacos注册与发现及源码注册流程

目录 概述nacos工程案例nacos服务注册案例版本说明本地启动 nacos-server搭建 spring cloud alibaba 最佳实践服务注册案例服务订阅案例 nacos注册源码流程源码关键点技巧 结束 概述 通过本文&#xff0c;学会如何确定项目组件版本(减少可能出现的jar包冲突)&#xff0c;nacos…

【Python】创建简单的Python微服务Demo与FastAPI

创建简单的Python微服务Demo与FastAPI 在微服务架构中&#xff0c;通过FastAPI框架创建一个简单的Python微服务Demo涉及多个步骤&#xff0c;包括定义服务、使用框架、进行通信等。在这篇文章中&#xff0c;我们将使用FastAPI框架创建两个简单的微服务&#xff0c;它们通过RES…

12月5日星期二今日早报简报微语报早读

12月5日星期二&#xff0c;农历十月廿三&#xff0c;早报微语早读。 1、国家卫健委&#xff1a;各地基层医卫机构要全面向儿童开放&#xff0c;不得拒诊&#xff1b; 2、五月天演唱会被指假唱&#xff0c;上海文旅局执法总队&#xff1a;已要求五月天演唱会主办方配合调查&am…

The Sandbox 携手 Sandsoft,与 Nuqtah 合作推动沙特阿拉伯的 Web3 发展

新的合作伙伴关系将增强创作者的能力&#xff0c;促进区块链生态系统的包容性。 The Sandbox 及其合作伙伴 Sandsoft 是移动游戏开发商和发行商&#xff0c;也是 AAA 人才驱动的投资者&#xff0c;他们非常高兴地宣布与 Nuqtah 建立新的合作伙伴关系&#xff0c;Nuqtah 是中东和…

MybatisPlus中的使用Wrapper自定义SQL

一、条件构造器 条件构造器提供了一种更加简洁和直观的方式来构建复杂的查询条件。它提供了一组静态方法&#xff0c;用于构建各种类型的查询条件&#xff0c;包括等于、不等于、大于、小于、包含等。使用条件构造器可以避免手动拼接SQL语句的麻烦&#xff0c;提高代码的可读性…

树莓派Python程序开机自启动(Linux下Python程序开机自启动)

前一阵子用python编写了一个驱动I2C程序读写屏幕&#xff0c;输出IP的小程序&#xff0c;程序编好后需要树莓派使能程序开机自启动。其实这些方法对任何Linux系统都适用。 方法一&#xff1a;此方法的缺点是不进入默认pi的账号&#xff0c;甚至不开hdmi开启桌面的话&#xff0…

关于栈的简单理解

1. 栈(Stack) 1.1 文字讲解 栈&#xff1a;一种特殊的线性表&#xff0c;其只允许在固定的一端进行插入和删除元素操作。进行数据插入和删除操作的一端称为栈顶&#xff0c;另一端称为栈底。栈中的数据元素遵守后进先出LIFO&#xff08;Last In First Out&#xff09;的原则&a…

IP5316 2.4A 充电、2.4 A 放电、集成 DCP 功能移动电源 SOC

IP5316 2.4A 充电、 2.4 A 放电、集成 DCP 功能移动电源 SOC 简介&#xff1a; IP5316 是一款集成升压转换器、锂电池充电管理、电池电量指示的多功能电源管理 SOC&#xff0c;为移动电源提供完整的电源解决方案。得益于 IP5316 的高集成度与丰富功能&#xff0c;使其在应用时…

零信任组件和实施

零信任是一种安全标准&#xff0c;其功能遵循“从不信任&#xff0c;始终验证”的原则&#xff0c;并确保没有用户或设备受信任&#xff0c;无论他们是在组织网络内部还是外部。简而言之&#xff0c;零信任模型消除了信任组织安全边界内任何内容的概念&#xff0c;而是倡导严格…

外包干了2个月,技术明显退步了...

先说一下自己的情况&#xff0c;大专生&#xff0c;19年通过校招进入广州某软件公司&#xff0c;干了接近5年的功能测试&#xff0c;今年11月份&#xff0c;感觉自己不能够在这样下去了&#xff0c;长时间呆在一个舒适的环境会让一个人堕落!而我已经在一个企业干了四年的功能测…

JS实现成才网注册系统(网页数据验证)

主代码 <!DOCTYPE htmlPUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns"http://www.w3.org/1999/xhtml"><head><meta http-equiv"Conten…