文件操作工具类常用方法

一、依赖

<!--压缩和解压使用到的jar包-->
<dependency>
    <groupId>org.apache.ant</groupId>
    <artifactId>ant</artifactId>
    <version>1.10.9</version>
</dependency>

二、工具类代码

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.zip.ZipOutputStream;

/**
 * @Date: 2021/8/18
 * 文件操作工具类
 */
public class FolderAndFileUtils {
    private static Logger logger = LoggerFactory.getLogger(FolderAndFileUtils.class);
    /**
     * 空格缩进符
     */
    private static String SPACE = "   ";

    /**
     * 将文件夹下的内容拷贝
     * @param fromPath 模板文件夹路径
     * @param toPath 目标文件夹路径
     * @throws Exception
     */
    public static void copyFolder(String fromPath,String toPath) throws Exception {
        //源文件夹路径
        File sourceFile = new File(fromPath);
        //目标文件夹路径
        File targetFile = new File(toPath);
        if(!sourceFile.exists()){
            logger.error("源文件夹不存在");
            throw new Exception("源文件夹不存在");
        }
        if(!sourceFile.isDirectory()){
            logger.error("源文件夹不是目录");
            throw new Exception("源文件夹不是目录");
        }
        if(!targetFile.exists()){
            //目标文件夹不存在就创建
            targetFile.mkdirs();
        }
        if(!targetFile.isDirectory()){
            logger.error("目标文件夹不是目录");
            throw new Exception("目标文件夹不是目录");
        }
        File[] files = sourceFile.listFiles();
        if(files == null || files.length == 0){
            return;
        }
        for(File file : files){
            //文件要复制的路径
            String movePath = targetFile + File.separator + file.getName();
            if(file.isDirectory()){
                //如果是目录则递归调用
                copyFolder(file.getAbsolutePath(),movePath);
            }else {
                //如果是文件则复制文件
                copy(file.getAbsolutePath(),movePath);
            }
        }
    }

    /**
     * 输出文件到指定目录
     * @param jsonStr json字符串
     * @param dir 文件保存位置如:D:/project/
     * @param fileName 文件名称 xxx.js
     * @param var js文件中变量名 const config = {}
     */
    public static void outPutJsonDataToPath(String jsonStr,String dir,String fileName,String var) throws Exception {
        String path = dir + fileName;
        //判断文件是否存在
        File file = new File(path);
        try {
            //判断文件是否已经存在
            if (file.exists()) {
                //删除原文件
                file.delete();
            } else {
                //创建新文件
                file.createNewFile();
            }
            //格式化字符串
            String content = formatJson(jsonStr);
            Writer write = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
            write.write(var);
            write.write(content);
            write.flush();
            write.close();
            logger.info(fileName + " 保存到 " + dir + " 成功");
        } catch (Exception e) {
            logger.error(fileName + " 保存到 " + dir + " 失败");
            throw new Exception("文件保存到指定位置异常");
        }
    }

    /**
     * 指定路径生成文件夹
     * @param path
     */
    public static void createFolder(String path) {
        //判断文件是否存在
        File dir = new File(path);
        if(!dir.exists()){
            dir.mkdir();
        }
    }

    /**
     * 压缩文件
     * @param fromPath 源文件路径
     * @param toPath 压缩后文件存储路径
     */
    public static void compressToZip(String fromPath, String toPath) {
        File sourceFile = new File(fromPath);
        File zipPath = new File(toPath);
        if (!zipPath.exists()) {
            zipPath.mkdirs();
        }
        String zipName = sourceFile.getName() + ".zip";
        File zipFile = new File(zipPath + File.separator + zipName);
        ZipOutputStream zos = null;
        try {
            zos = new ZipOutputStream(new FileOutputStream(zipFile));
            writeZip(sourceFile, "", zos);
            //文件压缩完成后,删除被压缩文件
            // boolean flag = deleteDir(sourceFile);
            // log.info("删除被压缩文件[" + sourceFile + "]标志:{}", flag);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage(), e.getCause());
        } finally {
            try {
                if (zos != null) {
                    //关闭资源
                    zos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 方式一:使用org.apache.tools包下的类进行解压
     * 解压文件夹zip格式
     * @param fileName 文件夹名称
     * @param destDirPath 文件夹路径
     */
    public static void unZip(String fileName, String destDirPath) {
        long start = System.currentTimeMillis();
        File srcFile = new File(destDirPath + fileName);
        //判断源文件是否存在
        if (!srcFile.exists()) {
            throw new RuntimeException(srcFile.getPath() + "所指文件不存在");
        }
        //开始解压
        ZipFile zipFile = null;
        try {
            //解决zip文件中有中文目录或者中文文件。设置字符编码为GBK
            zipFile = new ZipFile(srcFile, String.valueOf(Charset.forName("GBK")));
            Enumeration<?> entries = zipFile.getEntries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                System.out.println("解压" + entry.getName());
                //如果是文件夹,就创建个文件夹
                if (entry.isDirectory()) {
                    String dirPath = destDirPath + "/" + entry.getName();
                    File dir = new File(dirPath);
                    dir.mkdirs();
                } else {
                    //如果是文件,就先创建一个文件,然后用io流把内容copy过去
                    File targetFile = new File(destDirPath + "/" + entry.getName());
                    //保证这个文件的父文件夹必须要存在
                    if (!targetFile.getParentFile().exists()) {
                        targetFile.getParentFile().mkdirs();
                    }
                    targetFile.createNewFile();
                    //将压缩文件内容写入到这个文件中
                    InputStream is = zipFile.getInputStream(entry);
                    FileOutputStream fos = new FileOutputStream(targetFile);
                    int len;
                    byte[] buf = new byte[1024];
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                    }
                    // 关流顺序,先打开的后关闭
                    fos.close();
                    is.close();
                }
            }
            long end = System.currentTimeMillis();
            System.out.println("解压完成,耗时:" + (end - start) + " ms");
        } catch (Exception e) {
            throw new RuntimeException("unzip error from ZipUtils", e);
        } finally {
            if (zipFile != null) {
                try {
                    zipFile.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 下载文件(图片)到指定路径
     * @param downloadUrl 文件链接地址
     * @param filePath 文件保存路径
     * @param filename 保存文件名
     */
    public static void downloadImg(String downloadUrl, String filePath, String filename) {
        URL url = null;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            url = new URL(downloadUrl);
            //打开连接
            URLConnection con = url.openConnection();
            //设置请求超时时间5s
            con.setConnectTimeout(5 * 1000);
            inputStream = con.getInputStream();
            //创建字节数组
            byte[] bytes = new byte[1024];
            //读取到的数据长度
            int length;
            File file = new File(filePath);
            if (!file.exists()) {
                //如果不存在当前文件夹,则创建该文件夹
                boolean mkdir = file.mkdirs();
                if (!mkdir) {
                    return;
                }
            }
            outputStream = new FileOutputStream(file.getPath() + "\\" + filename);
            //读取
            while ((length = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, length);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 返回格式化JSON字符串
     * @param json 未格式化的JSON字符串
     * @return 格式化的JSON字符串
     */
    private static String formatJson(String json) {
        StringBuffer result = new StringBuffer();
        int length = json.length();
        //记录缩进次数
        int number = 0;
        char key = 0;
        //遍历字符串
        for (int i = 0; i < length; i++) {
            //获取当前字符
            key = json.charAt(i);
            //如果当前字符是前方括号、前花括号做如下处理
            if ((key == '[') || (key == '{')) {
                //如果前面还有字符,并且字符为“:”,打印:换行和缩进字符字符串
                if ((i - 1 > 0) && (json.charAt(i - 1) == ':')) {
                    result.append('\n');
                    result.append(indent(number));
                }
                //拼接当前字符
                result.append(key);
                //前方括号、前花括号的后面必须换行
                result.append('\n');
                //每出现一次前方括号、前花括号;缩进次数增加一次
                number++;
                result.append(indent(number));
                //进行下一次循环。
                continue;
            }
            //如果当前字符是后方括号、后花括号做如下处理
            if ((key == ']') || (key == '}')) {
                //后方括号、后花括号的前面必须换行
                result.append('\n');
                //每出现一次后方括号、后花括号缩进次数减少一次
                number--;
                result.append(indent(number));
                //拼接当前字符。
                result.append(key);
                //如果当前字符后面还有字符,并且字符不为“,”就换行
                if (((i + 1) < length) && (json.charAt(i + 1) != ',')) {
                    result.append('\n');
                }
                //继续下一次循环
                continue;
            }
            //如果当前字符是逗号,逗号后面换行并缩进不改变缩进次数
            if ((key == ',')) {
                result.append(key);
                result.append('\n');
                result.append(indent(number));
                continue;
            }
            //拼接当前字符
            result.append(key);
        }
        return result.toString();
    }

    /**
     * 返回指定次数的缩进字符串,每一次缩进三个空格,即SPACE
     * @param number 缩进次数
     * @return 指定缩进次数的字符串
     */
    private static String indent(int number) {
        StringBuffer result = new StringBuffer();
        for (int i = 0; i < number; i++) {
            //追加缩进
            result.append(SPACE);
        }
        return result.toString();
    }

    /**
     * 拷贝文件
     * @param fromPath
     * @param toPath
     */
    private static void copy(String fromPath,String toPath) {
        BufferedInputStream dis = null;
        BufferedOutputStream dos = null;
        try {
            FileInputStream fis = new FileInputStream(fromPath);
            FileOutputStream fos = new FileOutputStream(toPath);

            dis = new BufferedInputStream(fis);
            dos = new BufferedOutputStream(fos);

            //定义一个数组保存字节数据
            byte[] b = new byte[1024];
            //定义一个int变量len记录读取到的有效个数,如果读到文件末尾了,返回-1
            int len = 0;
            //遍历读取数据并将数据写入指定目的路径
            while((len = dis.read(b)) != -1){
                dos.write(b, 0, len);
                dos.flush();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                if(dos != null){
                    //关闭资源
                    dos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(dis != null){
                    //关闭资源
                    dis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 遍历所有文件,压缩
     * @param file 源文件目录
     * @param parentPath 压缩文件目录
     * @param zos 文件流
     */
    private static void writeZip(File file, String parentPath, ZipOutputStream zos) {
        if (file.isDirectory()) {
            //目录
            parentPath += file.getName() + File.separator;
            File[] files = file.listFiles();
            for (File f : files) {
                writeZip(f, parentPath, zos);
            }
        } else {
            BufferedInputStream bis = null;
            //文件
            try {
                bis = new BufferedInputStream(new FileInputStream(file));
                //指定zip文件夹
                ZipEntry zipEntry = new ZipEntry(parentPath + file.getName());
                zos.putNextEntry(zipEntry);
                //设置压缩文件编码格式,使用GBK编码可以避免压缩中文文件名乱码
                zos.setEncoding("GBK");
                int len;
                byte[] buffer = new byte[1024 * 10];
                while ((len = bis.read(buffer, 0, buffer.length)) != -1) {
                    zos.write(buffer, 0, len);
                    zos.flush();
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException(e.getMessage(), e.getCause());
            } finally {
                try {
                    if (bis != null) {
                        //关闭资源
                        bis.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 删除文件夹
     * @param dir
     * @return
     */
    private 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();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值