1. 程式人生 > >檔案壓縮工具類

檔案壓縮工具類

將檔案列表打包為zip

/**
     * 將拉取的檔案打包為zip
     * @param filePathList 檔案路徑列表
     * @param savePath 儲存路徑
     * @param zipName zip名稱
     * @return zip路徑
     */
    public String generateZip(ArrayList<String>filePathList,String savePath,String zipName) throws IOException{
        String zipPath=savePath+"/"+zipName;
        File zip =new File(zipPath);
        FileOutputStream outputStream=new FileOutputStream(zip);
        ZipOutputStream out =new ZipOutputStream(outputStream);
        filePathList.forEach(row->{
                //要壓縮的單個檔案路徑
                String oneFilePath = row;
                File inputFile = new File(oneFilePath);
                //生成zip包中的zip實體
                ZipEntry zipEntry=new ZipEntry(inputFile.getName());
                try {
                    byte[] buffer = new byte[1024];
                    FileInputStream fileInputStream=new FileInputStream(oneFilePath);
                    out.putNextEntry(zipEntry);
                    int len;
                    //讀入需要下載的檔案的內容,打包到zip檔案
                    while ((len = fileInputStream.read(buffer)) != -1) {
                        out.write(buffer, 0, len);
                    }
                    fileInputStream.close();
                }catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        });
        out.closeEntry();
        out.close();
        return  zipPath;
    }