JAVA多個文件壓縮成zip

思路:

1.得到需要壓縮的文件列表。

2.壓縮生成zip文件。

3.刪除原始文件。

4.返回zip文件路徑。

----------------------------------------------------------分割線-----------------------------------------------------------------

不廢話,直接上代碼:

public String getZipFile(){
    String filePath = "D:/";
    String zipFileName = "D:/test/test.zip";
    File file = new File(filePath);

    List<String> files = new ArrayList<>;

    //獲取文件列表,此處省略

    ......
    File zipFile = new File(zipFileName);
    File fileParent = zipFile.getParentFile();
    if(!fileParent.exists()){
        fileParent.mkdirs();
    }
    exportZip(files,zipFile);
    return zipFileName;
}


**
     * 打包成zip
     * @param fileNames
     * @param zip
     * @throws FileNotFoundException
     * @throws IOException
     */
    private void exportZip( List<String> fileNames, File zip) throws FileNotFoundException {
        //1.壓縮文件
        File srcFile[] = new File[fileNames.size()];
        for (int i = 0; i < fileNames.size(); i++) {
            srcFile[i] = new File(fileNames.get(i));
        }
        byte[] byt = new byte[1024];
        ZipOutputStream out = null;
        FileInputStream in = null;
        try {
            out = new ZipOutputStream(new FileOutputStream(zip), Charset.forName(CHARACTOR_CODE));
            for (int i = 0; i < srcFile.length; i++) {
                try{
                    in = new FileInputStream(srcFile[i]);
                    out.putNextEntry(new ZipEntry(srcFile[i].getName()));
                    int length;
                    while((length=in.read(byt)) > 0){
                        out.write(byt,0,length);
                    }
                    out.closeEntry();
                    in.close();
                }catch (Exception e){
                    LOGGER.info("文件打包失敗:{}",e);
                }finally{
                    try{
                        in.close();
                    }catch (Exception e1){
                        LOGGER.info("文件流關閉失敗:{}",e1);
                    }
                }

            }
            out.close();
        } catch (Exception e) {
            LOGGER.info("文件打包失敗,{}",e);
            throw new FileNotFoundException();
        }finally {
            try {
                out.close();
                in.close();
            } catch (IOException e) {
                LOGGER.info("文件流關閉失敗:{}",e);
            }
        }
        //2.刪除服務器上的臨時文件(excel)
        for (int i = 0; i < srcFile.length; i++) {
            File temFile = srcFile[i];
            if(temFile.exists() && temFile.isFile()){
                try{
                    temFile.delete();
                }catch(Exception e){
                    LOGGER.info("文件刪除出錯:{}",e);
                }

            }
        }
    }


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