Java解决InputStream流重复使用问题【100%解决】

本文分享了如何解决在上传文件到阿里云OSS时遇到的InputStream流导致文件大小为0KB的问题,通过实例展示了正确的数据流复制方法,包括转换 InputStream 到 ByteArrayOutputStream 和避免内存泄露。关键在于正确处理流的读取和关闭,确保数据完整上传。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

背景

我在做上传文件的时候,第一步要读取文件中的数据进行分析校验,第二步,校验通过后需求将源文件上传OSS,然后使用同一个InputStream流,发现上传OSS的文件为0kb了。

本博客同事解决上传OSS文件为0kb等问题

你在网上找的 将InputStream 转化成ByteArrayInputStream 然后再次调用使用,我可以负责任告诉你,没用,已经测试过。以下例句没用的代码

/**
 * 转换为字节数组输入流,可以重复消费流中数据
 *
 * @param inputStream
 * @return
 * @throws IOException
 */
public static ByteArrayInputStream toByteArrayInputStream(InputStream inputStream) throws IOException {
    if (inputStream instanceof ByteArrayInputStream) {
        return (ByteArrayInputStream) inputStream;
    }

    try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
        BufferedInputStream br = new BufferedInputStream(inputStream);
        byte[] b = new byte[1024];
        for (int c; (c = br.read(b)) != -1; ) {
            bos.write(b, 0, c);
        }
        // 主动告知回收
        b = null;
        br.close();
        inputStream.close();
        return new ByteArrayInputStream(bos.toByteArray());
    }
}

真正解决方案:

private static  byte[] cloneInputStream(InputStream input) {
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = input.read(buffer)) > -1) {
            baos.write(buffer, 0, len);
        }
        baos.flush();
        baos.close()
        input.close()
        return baos.toByteArray();
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

调用:

 //存入上传文件到OSS
  byte[] bytes = cloneInputStream(inputStream); 
  InputStream fileInputStream = new ByteArrayInputStream(bytes);
  AliyunCloudStorageService storageService = new AliyunCloudStorageService(config);
  storageService.upload(fileInputStream, fileName, url);

 //读取文件 
  InputStream newInputStream = new ByteArrayInputStream(bytes);
        CsvReader csvReader = new CsvReader(new BufferedInputStream(newInputStream), Charset.forName("utf-8"));

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

叫兽-郭老师

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值