通过文件流解压压缩包

最近在做文件解压遇到个问题,记录下解决过程。

文件来源是通过接口获取文件流,然后通过文件流解压文件。

此时需要将文件流写入文件然后对文件进行操作,

遇到的问题是怎么创建合格File对象,搜索了很长时间不得解,

最后发现可以通过 createTempFile来创建

File file = File.createTempFile(fileName, suffix);

具体代码如下:

```java

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class ZipDemo {
    private static final Log log = LogFactory.getLog(ZipDemo.class);

    /**
     * 通过文件流解压文件
     *
     * @throws IOException e
     */
    public static void method() throws IOException {
        // inputStream为通过接口或者文件下载获取的文件流,此处为模拟数据
        ByteArrayOutputStream baos = null;
        FileOutputStream fos = null;
        try (InputStream inputStream = new FileInputStream(File.createTempFile("压缩文件", ".zip"));
             ZipInputStream zipInputStream = new ZipInputStream(inputStream)) {
            ZipEntry ze;
            while ((ze = zipInputStream.getNextEntry()) != null) {
                if (ze.isDirectory()) {
                    continue;
                }
                byte[] buf = new byte[1024];
                int length;
                baos = new ByteArrayOutputStream();
                while ((length = zipInputStream.read(buf)) != -1) {
                    baos.write(buf, 0, length);
                    baos.flush();
                }
                byte[] data = baos.toByteArray();
                // 文件名
                String fileName = "文件名";
                // 文件后缀
                String suffix = ".jpg";
                File file = File.createTempFile(fileName, suffix);
                file.deleteOnExit();
                fos = new FileOutputStream(file);
                fos.write(data);

                // 此时,file文件已经有了内容,可以对文件进行读写,上传下载等操作了
                fos.close();
                baos.close();
            }
        } catch (Exception e) {
            log.info("执行异常");
        } finally {
            if (fos != null) {
                fos.close();
            }
            if (baos != null) {
                baos.close();
            }
        }
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值