JAVA實現文件壓縮、解壓zip包及相關處理

說明

在jdk1.8版本中,已經提供了針對文件壓縮zip包的工具類。

1、壓縮文件集合到指定目錄

 

   /**
     * @Description 壓縮文件集合到指定的目錄
     **/
    public static void zipFiles(String zipFileName, String zipFilePath, List<FileDto> fileList) {
        logger.info("fileList -- > " + JSON.toJSONString(fileList));
        if(CollectionUtils.isEmpty(fileList)){
            logger.info("需要壓縮的文件爲空");
            return;
        }
        // 臨時文件
        File tempfile = new File(zipFilePath + File.separator + zipFileName);
        if(tempfile.exists()){
            tempfile.delete();
        }
        final InputStream input = null;
        ZipOutputStream zipOut = null;
        try {
            FileOutputStream fos = new FileOutputStream(tempfile);
            zipOut = new ZipOutputStream(fos);
            // zip的名稱爲
            zipOut.setComment(zipFileName);
//            zipOut.setEncoding("GBK");
            fileList.forEach(fileDto -> {
                byte [] fileBytes = getFileData(fileDto.getFilePath(), fileDto.getFileName());
                input = new ByteArrayInputStream(fileBytes);
                zipOut.putNextEntry(new ZipEntry(fileDto.getFileName()));
                int temp = 0;
                while ((temp = input.read()) != -1) {
                    zipOut.write(temp);
                }
            });
        }catch (IOException e) {
            e.printStackTrace();
        }
        finally{
            try {
                if (zipOut != null) {zipOut.close();}
                if (input != null) {input.close();}
            } catch (IOException e2) {
                e2.printStackTrace();
            }
        }
    }

2、解壓(暫未提供)

3、zip轉byte[]

注:若在壓縮zip包的方法體內將zip壓縮包轉byte[],需要先將ZipOutputStream流關閉。

 

/**
 *  文件轉byte[]
 */
public static byte[] fileToBytes(String path) {
    File file = new File(path);
    FileInputStream fis;
    try {
        fis = new FileInputStream(file);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] b = new byte[(int)file.length()];
        int n;
        while ((n = fis.read(b)) != -1) {
            bos.write(b, 0, n);
        }
        fis.close();
        bos.close();
        return bos.toByteArray();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;

}

4、byte[]轉zip 

/**
 * 字節流寫入文件
 */
public static void bytesToFile(byte[] data, String filePath) {
    File file = new File(filePath);
    if (!file.getParentFile().exists()) {
        file.getParentFile().mkdirs();
    }

    FileOutputStream o = null;
    try {
        o = new FileOutputStream(filePath);
        o.write(data, 0, data.length);
        o.flush();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (null != o) {
            try {
                o.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章