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 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 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);
                }

            }
        }
    }


你可能感兴趣的:(Java开发)