您现在的位置是:首页 > 文章详情

java之压缩流(ZipOutputStream)

日期:2018-07-18点击:415

一、文件压缩,是很有必要的,我们在进行文件,传输过程中,很多时候都是,都是单个文件单个文件发送接收,但是当数据量特别大,或者文件数量比较多的时候,这个时候就可以考虑文件压缩。

二、优势:文件压缩过后,只需要进行一次文件的传输就可以了。减少频繁发送的问题。缺点:文件大小会变大,如果传输过程中断了,风险较大。

三、实现:

/** * 提供给用户使用的基本压缩类 * @param srcPath * @param outPath * @throws IOException */ public static void compressFile(String srcPath, String outPath) throws IOException { //读取源文件 File srcFile = new File(srcPath); //判断输出路径是否正确 File outFile = new File(outPath); //如果只是路劲加入对应的压缩名称 if (outFile.isDirectory()) { //用"/"作文判断标准 if (outPath.endsWith(File.separator)) { outPath += srcFile.getName().split("\\.")[0] + ".zip"; } else { outPath += File.separator + srcFile.getName().split("\\.")[0] + ".zip"; } } //读取文件流 FileOutputStream fileOutputStream = new FileOutputStream(outPath); ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream); //压缩文件  compressFile(srcFile, srcFile.getName(),zipOutputStream); //关闭流  zipOutputStream.close(); fileOutputStream.close(); } /** * 迭代方式进行文件压缩 * @param file * @param fileName * @param outputStream * @throws IOException */ private static void compressFile(File file, String fileName, final ZipOutputStream outputStream) throws IOException { //如果是目录 if (file.isDirectory()) { //创建文件夹 outputStream.putNextEntry(new ZipEntry(fileName+"/")); //迭代判断,并且加入对应文件路径 File[] files = file.listFiles(); Iterator<File> iterator = Arrays.asList(files).iterator(); while (iterator.hasNext()) { File f = iterator.next(); compressFile(f, fileName+"/"+f.getName(), outputStream); } } else { //创建文件 outputStream.putNextEntry(new ZipEntry(fileName)); //读取文件并写出 FileInputStream fileInputStream = new FileInputStream(file); BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream); byte[] bytes = new byte[1024]; int n; while ((n = bufferedInputStream.read(bytes)) != -1) { outputStream.write(bytes, 0, n); } //关闭流  fileInputStream.close(); bufferedInputStream.close(); } }

四、测试:

public static void main(String[] args) throws IOException { compressFile("D:\\srv", "D:\\"); }

五、效果还是可以,此方式根据需要修改!

 

原文链接:https://yq.aliyun.com/articles/624245
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章