java 文件压缩、解压、复制、读取文件,文件写入内容工具类

1:文件压缩、

2:递归压缩文件、

3:下载单个文件、

4:删除单个文件、

5:解压文件到指定文件夹、

6:上传文件、

7:读取多级目录下的所有文件、

8:文件复制到另一个目录下

9:往文件里写内容

package com.ed.core.util;

import com.ed.core.commom.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.nio.file.Files;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

/**
 * @ProjectName: gitIdeaWork
 * @Package: com.ed.core.util
 * @ClassName: ZipOpUtil
 * @Author: zhao
 * @Description: 资源打包下载类 https://my.oschina.net/Rayn/blog/471309
 * @Date: 2020/2/21 16:50
 * @Version: 1.0
 *
 */
public class ZipOpUtil {

    private static Logger logger = LoggerFactory.getLogger(ZipOpUtil.class);

    public static void main(String[] args) {

        moveTotherFolders("C:\\Users\\zhao\\Desktop\\12121\\1.txt","C:\\Users\\zhao\\Desktop\\12121\\12\\");

        /*zipFile("C:\\Users\\zhao\\Desktop\\12121",new File("C:\\Users\\zhao\\Desktop\\56.tar"));
*/
        try {
            decompress("C:\\Users\\zhao\\Desktop\\56.tar","C:\\Users\\zhao\\Desktop\\56\\pp\\");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 将多个文件打包到一个zip中
     *
     * @param sourceFolder
     * @param zipFile
     * @return
     */
    public static boolean zipFile(String sourceFolder, File zipFile) {
        boolean isOk = true;
        File f = new File(sourceFolder);
        ZipOutputStream out = null;
        try {
            if (!f.exists()) {
                f.mkdirs();
            }
            out = new ZipOutputStream(new FileOutputStream(zipFile));
            zip(out, f, "");
            out.flush();
//            FileUtils.deleteDirectory(f);
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("压缩文件出错!");
        } finally {
            if (null != out) {
                try {
                    out.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println("压缩文件完成!!!");
        return isOk;
    }

    /**
     * 递归压缩文件
     *
     * @param out
     * @param f
     * @param base
     * @throws Exception
     */
    private static void zip(ZipOutputStream out, File f, String base) throws Exception {
        if (f.isDirectory()) {
            File[] fl = f.listFiles();
            out.putNextEntry(new ZipEntry(base + "/"));
            base = base.length() == 0 ? "" : base + "/";
            for (int i = 0; i < fl.length; i++) {
                zip(out, fl[i], base + fl[i].getName());
            }
        } else {
            out.putNextEntry(new ZipEntry(base));
            FileInputStream in = new FileInputStream(f);
            int b;
            logger.info(base);
            while ((b = in.read()) != -1) {
                out.write(b);
            }
            in.close();
        }
    }

    /**
     * 下载单个文件
     *
     * @param file
     * @param request
     * @param response
     * @return
     */
    public static boolean downFile(File file, HttpServletRequest request, HttpServletResponse response) {
        boolean isOk = true;
        OutputStream myout = null;
        FileInputStream fis = null;
        BufferedInputStream buff = null;
        HttpSession session = request.getSession();
        if (session != null) {
            session.setAttribute("state", "");
        }
        try {
            response.setContentType("application/x-msdownload");
            response.setContentLength((int) file.length());
            response.setHeader("content-disposition", "attachment;filename=" + new String(file.getName().getBytes("utf-8"), "ISO8859-1"));
            fis = new FileInputStream(file);
            buff = new BufferedInputStream(fis);
            byte[] b = new byte[1024 * 10];//相当于我们的缓存
            long k = 0;//该值用于计算当前实际下载了多少字节
            //从response对象中得到输出流,准备下载
            myout = response.getOutputStream();
            while (k < file.length()) {
                int j = buff.read(b, 0, b.length);
                k += j;
                //将b中的数据写到客户端的内存
                myout.write(b, 0, j);
            }
            myout.flush();
        } catch (Exception e) {
            e.printStackTrace();
            isOk = false;
        } finally {
            try {
                if (null != myout) {
                    myout.close();
                    myout = null;
                }
                if (null != buff) {
                    buff.close();
                    buff = null;
                }
                if (null != fis) {
                    fis.close();
                    fis = null;
                }
                if (file.exists()) {
                    ZipOpUtil.delFile(file);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return isOk;
    }

    /**
     * 删除单个文件
     *
     * @param file
     * @return
     */
    public static boolean delFile(File file) {
        boolean isOk = true;
        try {
            if (file.isFile() && file.exists()) {
                file.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
            isOk = false;
        } finally {
            // log ...
        }
        return isOk;
    }



    /**
     * 解压文件到指定文件夹
     *
     * @param zip      源文件
     * @param destPath 目标文件夹路径
     * @throws Exception 解压失败
     */
    public static void decompress(String zip, String destPath) throws Exception {
        //参数检查
        if (StringUtils.isEmpty(zip) || StringUtils.isEmpty(destPath)) {
            throw new IllegalArgumentException("zip or destPath is illegal");
        }
        File zipFile = new File(zip);
        if (!zipFile.exists()) {
            throw new FileNotFoundException("zip file is not exists");
        }
        File destFolder = new File(destPath);
        if (!destFolder.exists()) {
            if (!destFolder.mkdirs()) {
                throw new FileNotFoundException("destPath mkdirs is failed");
            }
        }
        ZipInputStream zis = null;
        BufferedOutputStream bos = null;
        try {
            zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(zip),1024));
            ZipEntry ze;
            while ((ze = zis.getNextEntry()) != null) {
                //得到解压文件在当前存储的绝对路径
                String filePath = destPath + File.separator + ze.getName();
                if (ze.isDirectory()) {
                    new File(filePath).mkdirs();
                } else {
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    byte[] buffer = new byte[1024];
                    int count;
                    while ((count = zis.read(buffer)) != -1) {
                        baos.write(buffer, 0, count);
                    }
                    byte[] bytes = baos.toByteArray();
                    File entryFile = new File(filePath);
                    //创建父目录
                    if (!entryFile.getParentFile().exists()) {
                        if (!entryFile.getParentFile().mkdirs()) {
                            throw new FileNotFoundException("zip entry mkdirs is failed");
                        }
                    }
                    //写文件
                    bos = new BufferedOutputStream(new FileOutputStream(entryFile));
                    bos.write(bytes);
                    bos.flush();
                }

            }
        } finally {
            closeQuietly(zis);
            closeQuietly(bos);
        }
    }

    private static void closeQuietly(final Closeable closeable) {
        try {
            if (closeable != null) {
                closeable.close();
            }
        } catch (final IOException ioe) {
            // ignore
        }
    }

    /**
     * 上传文件
     * @param file
     * @param path	文件路径
     * @return
     * @throws IOException
     */
    public static String upload(MultipartFile file, String path) throws IOException {
        String fileName = file.getOriginalFilename();
        int size = (int) file.getSize();
        logger.info(String.format("upload file: %s, size: %d", fileName, size));

        File dest = new File(path + "/" + fileName);

        if(!dest.getParentFile().exists()){ //判断文件父目录是否存在
            dest.getParentFile().mkdirs();
        }

        file.transferTo(dest);

        return fileName;
    }

    /**
     * @Author:
     * @Description:获取某个目录下所有直接下级文件,包括目录下的子目录的下的文件,所以用递归获取
     * @Date:
     */
    public static List<String> getFiles(String path, List<String> files) {
        File file = new File(path);
        File[] tempList = file.listFiles();

        for (int i = 0; i < tempList.length; i++) {
            if (tempList[i].isFile()) {
                files.add(tempList[i].toString());
                //文件名,不包含路径
                //String fileName = tempList[i].getName();
            }
            if (tempList[i].isDirectory()) {
                //这里就不递归了,
                getFiles(tempList[i].getPath(),files);
            }
        }
        return files;
    }

    /**
     * 文件复制到另一个目录下
     * @param startPath 文件所有目录:home/upload/file/hello.java
     * @param endPath   目的目录:home/upload/
     */
    public static void moveTotherFolders(String startPath,String endPath) {

        File src = new File(startPath);
        File dest = new File(endPath + src.getName());
        // 定义文件输入流和输出流对象
        FileInputStream fis = null;// 输入流
        FileOutputStream fos = null;// 输出流

        try {
            fis = new FileInputStream(src);
            fos = new FileOutputStream(dest);
            byte[] bs = new byte[1024];
            while (true) {
                int len = fis.read(bs, 0, bs.length);
                if (len == -1) {
                    break;
                } else {
                    fos.write(bs, 0, len);
                }
            }
            System.out.println("复制文件成功");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                fos.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                fis.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }


    /**
     * 往文件里写内容
     * @param list SQL集合
     */
    public static String writerFile(List<String> list,String time){
        String path = CommonConstant.FILE_ROOT + time + File.separator + "projectSql.sql";
        try {
            FileWriter fw = new FileWriter(path,false);
            if(list != null && list.size() > 0){
                for(int i = 0; i <list.size(); i++){
                    fw.write(list.get(i).toString() + ";\r\n");//windows中的换行为\r\n    unix下为\r。
                }
            }else{
                System.out.println("项目导出功能 - SQLList为空");
            }
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return path;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章