java压缩流的用法_Java对压缩包的操作(解压缩)

425115faf7b0

image

前言

如何用Java对文件进行加压和压缩

上篇文章说了项目中对根据URL提供的HTML代码中的文件URL进行下载,将下载后的文件存放在服务器上,但是文件下载下来都是ZIP压缩包。那么这篇就来看Java如何多文件进行解压缩操作。

一、正文

这里没有使用其他的jar包,利用Java中的IO流直接对文件进行操作,为了方便将文件放入桌面,路径为:C:\Users\Surpass\Desktop。

二、使用步骤

博主尽量在代码中添加明确的注释,以便于理解,所以直接贴代码了。

1.单文件压缩

/**

* @author Surpass

* @Package com.hkrt.demo.zip

* @Description: 单文件压缩

* @date 2020/10/16 10:51

*/

public class SingleZipCompression {

private static InputStream inputStream;

private static ZipOutputStream zipOutputStream;

private static OutputStream outputStream;

private static String filePath = "C:\\Users\\Surpass\\Desktop\\Linux就该这么学 高清晰PDF.pdf";

public static void main(String[] args) {

try {

//文件输入流

File file = new File(filePath);

inputStream = new FileInputStream(file);

//压缩输出路径的流 压缩文件路径+压缩文件名前缀(Linux就该这么学 高清晰PDF)+.zip

outputStream = new FileOutputStream(file.getParent()+"\\"+file.getName().substring(0,file.getName().lastIndexOf("."))+".zip");

zipOutputStream = new ZipOutputStream(outputStream);

//压缩包内文件的名字 Linux就该这么学 高清晰PDF.pdf

zipOutputStream.putNextEntry(new ZipEntry(file.getName()));

//输出文件

byte[] bytes = new byte[1024];

int len = 0;

while ((len = inputStream.read(bytes))!=-1){

zipOutputStream.write(bytes,0,len);

}

} catch (Exception e) {

e.printStackTrace();

}finally {

try {

if (zipOutputStream!=null){

zipOutputStream.closeEntry();

zipOutputStream.close();

}

if (outputStream!=null){

outputStream.close();

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值