栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在Java中将.zip压缩为.gz?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在Java中将.zip压缩为.gz?

我认为您可以为zip创建一个临时文件,将其添加到gzip,然后删除创建的zip。下面的代码示例应该可以帮助您。

public void ZIPandGZIP(String fileName, OutputStream os, String header) throws FileNotFoundException {    byte[] buffer = new byte[1024];    FileInputStream fis = null;    FileOutputStream fos = null;    ZipOutputStream zos = null;    File tempZipFile = File.createTempFile(fileName, ".zip")    try {        fos = new FileOutputStream(tempZipFile);        zos = new ZipOutputStream(fos);        ZipEntry ze = new ZipEntry(fileName);        zos.putNextEntry(ze);        fis = new FileInputStream(fileName);        int len;        while ((len = fis.read(buffer)) > 0) { zos.write(buffer, 0, len);        }        zos.closeEntry();    } catch (IOException ex) {        ex.printStackTrace();    } finally {        if (fis != null) { fis.close();        }        if (zos != null) { zos.close();        }        if (fos != null) { fos.close();        }    }    addGzipFileToStream(tempZipFile, os, header);}private void addGzipFileToStream(File zipFile, OutputStream os, String header) throws FileNotFoundException {    byte[] buffer = new byte[1024];    DataOutputStream dos = null;    GZIPOutputStream gzos = null;    FileInputStream inputStream = null;    try {        dos = new DataOutputStream(os);        dos.writeBytes(header);        gzos = new GZIPOutputStream(os);        inputStream = new FileInputStream(zipFile);        int len;        while ((len = inputStream.read(buffer)) > 0) { gzos.write(buffer, 0, len);        }        gzos.finish();    } catch (IOException ex) {        ex.printStackTrace();    } finally {        if (inputStream != null) { inputStream.close();        }        if (gzos != null) { gzos.close();        }        if (dos != null) { dos.close();        }        zipFile.delete();    }}

希望能帮助到你。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/428753.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号