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

Java之解压流(ZipInputStream)

日期:2018-07-19点击:481

一、ZipInputStream相对于ZipOutputStream而言,使用上面简单的多了,相对的,既然存在压缩流,就会存在,解压的方式。

二、解压文件,流的使用过程中也是很常用的,在读取文件,根据文件类型进行处理,这样,就可以做到,最低成本的数据传输了

三、解压例子

/** * 提供给用户使用的解压工具 * @param srcPath * @param outPath * @throws IOException */ public static void decompressionFile(String srcPath, String outPath) throws IOException { //简单判断解压路径是否合法 if (!new File(srcPath).isDirectory()) { //判断输出路径是否合法 if (new File(outPath).isDirectory()) { if (!outPath.endsWith(File.separator)) { outPath += File.separator; } //zip读取压缩文件 FileInputStream fileInputStream = new FileInputStream(srcPath); ZipInputStream zipInputStream = new ZipInputStream(fileInputStream); //解压文件  decompressionFile(outPath, zipInputStream); //关闭流  zipInputStream.close(); fileInputStream.close(); } else { throw new RuntimeException("输出路径不合法!"); } } else { throw new RuntimeException("需要解压的文件不合法!"); } } /** * ZipInputStream是逐个目录进行读取,所以只需要循环 * @param outPath * @param inputStream * @throws IOException */ private static void decompressionFile(String outPath, ZipInputStream inputStream) throws IOException { //读取一个目录 ZipEntry nextEntry = inputStream.getNextEntry(); //不为空进入循环 while (nextEntry != null) { String name = nextEntry.getName(); File file = new File(outPath+name); //如果是目录,创建目录 if (name.endsWith("/")) { file.mkdir(); } else { //文件则写入具体的路径中 FileOutputStream fileOutputStream = new FileOutputStream(file); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream); int n; byte[] bytes = new byte[1024]; while ((n = inputStream.read(bytes)) != -1) { bufferedOutputStream.write(bytes, 0, n); } //关闭流  bufferedOutputStream.close(); fileOutputStream.close(); } //关闭当前布姆  inputStream.closeEntry(); //读取下一个目录,作为循环条件 nextEntry = inputStream.getNextEntry(); } }

四、测试:

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

 

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

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

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

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

文章评论

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

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章