zip打包方法【用于打包到服务上的zip】

package com.fifedu.kyxl.column.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

/**
 * @author 
 */
public class ZipUtil {
    private static final int BUFFER_SIZE = 2 * 1024;
    /**
     * 是否保留原来的目录结构
     * true:  保留目录结构;
     * false: 所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
     */
    private static final boolean KeepDirStructure = true;
    private static final Logger log = LoggerFactory.getLogger(ZipUtil.class);

    public static void main(String[] args) {
        try {
            String aa = "C:/Users/boliu17/Desktop/boliu17";
            String bb = "C:/Users/boliu17/Desktop/boliu17.zip";
            toZip(aa,bb ,true);
            //toZip("E:\\download2\\2\\1\\000000\\6a5ca91540704725bafa9f1376d11ad4\\161367551fbd40c28b130aad7ad1f743\\75115a49031c41738c60056f29f24744\\01392b321e064295b2249740dd5449da\\level\\cf37cb4256e2456f982f04ca85bf4469", "E:\\download2\\2\\1\\000000\\6a5ca91540704725bafa9f1376d11ad4\\161367551fbd40c28b130aad7ad1f743\\75115a49031c41738c60056f29f24744\\01392b321e064295b2249740dd5449da\\level\\cf37cb4256e2456f982f04ca85bf4469.zip",false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 压缩成ZIP
     * @param srcDir         压缩 文件/文件夹 路径
     * @param outPathFile    压缩 文件/文件夹 输出路径+文件名 D:/xx.zip
     * @param isDelSrcFile   是否删除原文件: 压缩前文件
     */
    public static void toZip(String srcDir, String outPathFile,boolean isDelSrcFile) throws Exception {
        long start = System.currentTimeMillis();
        FileOutputStream out = null;
        ZipOutputStream zos = null;
        try {
            out = new FileOutputStream(new File(outPathFile));
            zos = new ZipOutputStream(out);
            File sourceFile = new File(srcDir);
            if(!sourceFile.exists()){
                throw new Exception("需压缩文件或者文件夹不存在");
            }
            compress(sourceFile, zos, sourceFile.getName(),true);
            if(isDelSrcFile){
                delDir(srcDir);
            }
            log.info("原文件:{}. 压缩到:{}完成. 是否删除原文件:{}. 耗时:{}ms. ",srcDir,outPathFile,isDelSrcFile,System.currentTimeMillis()-start);
        } catch (Exception e) {
            log.error("zip error from ZipUtils: {}. ",e.getMessage());
            throw new Exception("zip error from ZipUtils");
        } finally {
            try {
                if (zos != null) {zos.close();}
                if (out != null) {out.close();}
            } catch (Exception e) {}
        }
    }

    /**
     * 递归压缩方法
     * @param sourceFile 源文件
     * @param zos zip输出流
     * @param name 压缩后的名称
     */
    private static void compress(File sourceFile, ZipOutputStream zos, String name,boolean isFirst)
            throws Exception {
        byte[] buf = new byte[BUFFER_SIZE];
        if (sourceFile.isFile()) {
            zos.putNextEntry(new ZipEntry(name));
            int len;
            FileInputStream in = new FileInputStream(sourceFile);
            while ((len = in.read(buf)) != -1) {
                zos.write(buf, 0, len);
            }
            zos.closeEntry();
            in.close();
        } else {
            File[] listFiles = sourceFile.listFiles();
            if (listFiles == null || listFiles.length == 0) {
                if (KeepDirStructure) {
                    zos.putNextEntry(new ZipEntry(name + "/"));
                    zos.closeEntry();
                }
            } else {
                for (File file : listFiles) {
                    if (KeepDirStructure) {
                        if(isFirst){
                            compress(file, zos,  file.getName(),false);
                        }else {
                            compress(file, zos,  name + "/" + file.getName(),false);
                        }
                    } else {
                        compress(file, zos, file.getName(),false);
                    }
                }

            }
        }
    }

    /**
     * 解压文件到指定目录
     */
    @SuppressWarnings({ "rawtypes", "resource" })
    public static List<String> unZipFiles(String zipPath, String descDir) throws IOException {
        log.info("文件:{}. 解压路径:{}. 解压开始.",zipPath,descDir);
        long start = System.currentTimeMillis();
        List<String> path = new ArrayList<>();
        try{
            File zipFile = new File(zipPath);
            System.out.println(zipFile.getName());
            if(!zipFile.exists()){
                throw new IOException("需解压文件不存在.");
            }
            File pathFile = new File(descDir);
            if (!pathFile.exists()) {
                pathFile.mkdirs();
            }
            ZipFile zip = new ZipFile(zipFile, Charset.forName("GBK"));
            for (Enumeration entries = zip.entries(); entries.hasMoreElements();) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                String zipEntryName = entry.getName();
                path.add(zipEntryName);
                System.out.println(zipEntryName);
                InputStream in = zip.getInputStream(entry);
                String outPath = (descDir + File.separator + zipEntryName).replaceAll("\\*", "/");
                System.out.println(outPath);
                // 判断路径是否存在,不存在则创建文件路径
                File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
                if (!file.exists()) {
                    file.mkdirs();
                }
                // 判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
                if (new File(outPath).isDirectory()) {
                    continue;
                }
                // 输出文件路径信息
                OutputStream out = new FileOutputStream(outPath);
                byte[] buf1 = new byte[1024];
                int len;
                while ((len = in.read(buf1)) > 0) {
                    out.write(buf1, 0, len);
                }
                in.close();
                out.close();
            }
            log.info("文件:{}. 解压路径:{}. 解压完成. 耗时:{}ms. ",zipPath,descDir,System.currentTimeMillis()-start);
        }catch(Exception e){
            log.info("文件:{}. 解压路径:{}. 解压异常:{}. 耗时:{}ms. ",zipPath,descDir,e,System.currentTimeMillis()-start);
            throw new IOException(e);
        }
        return path;
    }


    /**
     * 解压文件到指定目录
     */
    public static List<String> zipFileString(String zipPath, String descDir) throws IOException {
        List<String> path = new ArrayList<>();
        try{
            File zipFile = new File(zipPath);
            System.err.println(zipFile.getName());
            if(!zipFile.exists()){
                throw new IOException("需解压文件不存在.");
            }
            File pathFile = new File(descDir);
            if (!pathFile.exists()) {
                pathFile.mkdirs();
            }
            ZipFile zip = new ZipFile(zipFile, Charset.forName("GBK"));
            for (Enumeration entries = zip.entries(); entries.hasMoreElements();) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                String zipEntryName = entry.getName();
                path.add(zipEntryName);
            }
        }catch(Exception e){
            throw new IOException(e);
        }
        return path;
    }

    // 删除文件或文件夹以及文件夹下所有文件
    public static void delDir(String dirPath) throws IOException {
        log.info("删除文件开始:{}.",dirPath);
        long start = System.currentTimeMillis();
        try{
            File dirFile = new File(dirPath);
            if (!dirFile.exists()) {
                return;
            }
            if (dirFile.isFile()) {
                dirFile.delete();
                return;
            }
            File[] files = dirFile.listFiles();
            if(files==null){
                return;
            }
            for (int i = 0; i < files.length; i++) {
                delDir(files[i].toString());
            }
            dirFile.delete();
            log.info("删除文件:{}. 耗时:{}ms. ",dirPath,System.currentTimeMillis()-start);
        }catch(Exception e){
            log.info("删除文件:{}. 异常:{}. 耗时:{}ms. ",dirPath,e,System.currentTimeMillis()-start);
            throw new IOException("删除文件异常.");
        }
    }


    /**
     * 复制一个目录及其子目录、文件到另外一个目录
     * @param src 文件
     * @param dest 目标目录
     * @throws IOException
     */
    public static void copyFolder(File src, File dest) throws IOException {
        if (src.isDirectory()) {
            if (!dest.exists()) {
                dest.mkdir();
            }
            String files[] = src.list();
            for (String file : files) {
                File srcFile = new File(src, file);
                File destFile = new File(dest, file);
                // 递归复制
                copyFolder(srcFile, destFile);
            }
        } else {
            if (!dest.exists()) {
                //dest.mkdir();
                dest.createNewFile();
            }
            InputStream in = new FileInputStream(src);
            OutputStream out = new FileOutputStream(dest);

            byte[] buffer = new byte[1024];

            int length;

            while ((length = in.read(buffer)) > 0) {
                out.write(buffer, 0, length);
            }
            in.close();
            out.close();
        }
    }



    /**
     * @Description:递归获取某个目录下所有直接下级文件,包括目录下的子目录的下的文件
     * @Date:
     */
    public static List<String> getFiles(String path,List<String> files) {
        File file = new File(path);
        File[] tempList = file.listFiles();
        if(tempList == null || tempList.length==0){
            return files;
        }
        for (int i = 0; i < tempList.length; i++) {
            if (tempList[i].isFile()) {
                files.add(tempList[i].toString());
                continue;
            }
            if (tempList[i].isDirectory()) {
                String tempPath = path + "/" + tempList[i].getName();
                //递归获取
                getFiles(tempPath,files);
            }
        }
        return files;
    }

}

ZipUtil.tozip方法(临时目录、需要打包的目径、打包完后删除临时目录)参数含义

新建文件到临时目录可以参考下方代码中的 FileUtils.copyFileUsingFileChannels

package com.fifedu.kyxl.column.util;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

public class FileUtils {

    /**如果没有当前目录则创建**/
    public static boolean creatDir(String destDirName){
        boolean flag = false;
        File dir = new File(destDirName);
        if (dir.exists()) {
            flag = true;
        }else{
            //File.separator---windows是\,unix是/
            flag = dir.mkdirs();//创建目录
        }
        return flag;
    }


    /**
     *
     * @param source
     * @param dest
     * @throws IOException
     */
    /**
     * @describe OSS测试环境资源上传到线上环境
     * @author Yangtse | E-Mail: hjwei2@iflytek.com
     * @date 2021年08月27日 10:54
     * @param source 源路径
     * @param dest  目标路径
     * @throws IOException
     */
    public static void copyFileUsingFileChannels(File source, File dest) throws IOException {

        FileChannel inputChannel = null;
        FileChannel outputChannel = null;
        try {
            inputChannel = new FileInputStream(source).getChannel();
            outputChannel = new FileOutputStream(dest).getChannel();
            outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
        } finally {
            inputChannel.close();
            outputChannel.close();
        }
    }



    public static boolean existsFileCheck(String filePath){
        boolean flag = false;
        File file = new File(filePath);
        if(file.isDirectory()){
            File [] foders = file.listFiles();
            if(foders != null && foders.length > 0){
                for (int i = 0; i < foders.length; i++) {
                    File foder = foders[i];
                    if(foder.isDirectory()){
                        File [] files = foder.listFiles();
                        if(files != null && files.length > 0){
                            for (int j = 0; j < files.length; j++) {
                                File temp = files[i];
                                if(temp.isFile()){
                                    flag = true;
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
        return flag;
    }



    public static void downloadRemoteFile(String sourceUrl, String destUrl){
        BufferedInputStream bis=null;
        BufferedOutputStream bos=null;
        try {
            URL url = new URL(sourceUrl);
            HttpURLConnection connection =  (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            InputStream is = connection.getInputStream();

            bis = new BufferedInputStream(is);

            File file = new File(destUrl);//名字截取 可以省略
            FileOutputStream fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            int b = 0;
            byte[] byArr = new byte[1024*4];
            while((b=bis.read(byArr))!=-1){
                bos.write(byArr, 0, b);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                if(bis!=null){
                    bis.close();
                }
                if(bos!=null){
                    bos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }




    public static void main(String[] args) {
        String ss = " developing of    is now  country   ";
        System.out.println(ss.trim());
        String dirs = "/cf8e6124054a4e1c843c15ce7b158eb2/b8003ef9cec94e918f981d0ed9df7aff/0003b2a82c7244d9865dfbcac09a841c";
        String [] arr = null;
        if(dirs.indexOf("/") != -1){
            arr = dirs.split("/");
        }else{
            arr = new String[1];
            arr[0] = dirs;
        }

        String sr = "D:\\kyxl\\resource\\test2\\2\\2\\2811000226000000690\\null\\83242bd3624d466a9a74e52b82241f3f\\level\\28591da9172c4c61b755ad38f0c17fd5";
        if(existsFileCheck(sr)){
            System.out.println("存在即合理");
        }

        String ff = "{\"questions\":[{\"analyse\" : \"\",\"audioPerson\" : \"henry\",\"audioTempo\" : \"medium\",\"audioType\" : \"1\",\"description\" : \"\",\"mainidea\" : \"\",\"paraphraseContent\" : \"\",\"phonetic\" : \"\",\"photo\" : \"\",\"recordingTime\" : \"\",\"res_path\" : \"20170702/37077949418694781.mp3\",\"roePath\" : \"\",\"text\" : \"\",\"tips\" : \"\",\"title\" : \"over three centuries English gradually swallowed French, and by the end of the 15th century what had developed was a modified, greatly enriched language--Middle English--with about 10,000 \"borrowed\" French words. \",\"title_cn\" : \"\"}],\"sample\":\"\"}";
        System.out.println(ff);
        String jj = ff.replaceAll("\r", ff);
        System.out.println(jj);

        String sse = " [number_replace]\n1919/nineteen nineteen/\n1922/nineteen twenty two/";
        //String text = tweet.getText();
        //String text = "Lesson .7. Too late .First listen and then answer the question.Did the detectives save the diamonds?The plane was late and detectives were waiting at the airport all morning. They were expecting a valuable parcel of diamonds from South Africa. A few hours earlier, someone had told the police that thieves would try to steal the diamonds. When the plane arrived, .5. some of the detectives were waiting inside the main building while others were waiting on the airfield. Two men took the parcel off the plane and carried it into the Customs House. While two detectives were keeping guard at the door, two others opened the parcel. To their surprise, the precious parcel was full of stones and sand!";
        String text = "Of course, \"the experts of the 1950's\" and the 1960s were also giving good reasons for doubting that those records would ever be broken, so why shouldn't the experts of today be wrong? The situation has, however, changed significantly in the last half-century. Bannister did his own research at a time when sports theory was imperfectly developed. Today, highly-qualified experts and professionals have a much better understanding of the physiology of the human body, based on decades of research, backed by millions of dollars of funding, and assisted by previously unheard-of technology.";
        //StringTokenizer st = new StringTokenizer(text," ,?.!:\"\"''\n#");
//        StringTokenizer st = new StringTokenizer(text," ,?.!:\"\"\n#");
//        List<String> wordList = new ArrayList<>();
//        while (st.hasMoreElements()) {
//            wordList.add(st.nextToken().toLowerCase());
//        }
//        System.out.println(wordList.size());
        String sourceUrl = "https://ktest.fifedu.com/static/upload/media/20220525/4820156094890693.mp3";
        String destUrl = "D:\\fifshare\\kyxl\\static\\upload\\temp_source\\2\\2\\2811000226000000690\\AHHF712\\6da15ea38a304230a66c4c45529a57c3\\20220608\\4820156094890693.mp3";
        //copyFileUsingFileChannels(new File(sourceUrl), new File(destUrl));
        downloadRemoteFile(sourceUrl, destUrl);
    }






}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值