InputStream可重复读,InputStream和String互转

本文介绍如何在Java中处理InputStream,尤其是当需要将InputStream转化为String并保持可重复读取的能力时。通过使用Base64进行编码和解码,可以实现InputStream到String的转换,并能确保转换后的InputStream内容不变。

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

java中的InputStream是不可重复读的,现在项目中需要从其他系统中得到一个InputStream对象进行操作。思路是将InputStream转为String字符串,之后在转回来,要想得到完全一样的InputStream,必须要进行编码和解码。

用Base64将InputStream对象编码后转换为String字符串

	/*
	*	InputStream转字符串
	*/
    public  String inputstrToStr(InputStream inputStream) throws IOException {
        byte[] bytes = new byte[0];
        bytes = new byte[inputStream.available()];
        // 读取文件内容到字节数组
        int offset = 0;
        int numRead = 0;
        while (offset < bytes.length
                && (numRead = inputStream.read(bytes, offset, bytes.length - offset)) >= 0) {
            offset += numRead;
        }
        // 读取完毕的校验
        if (offset < bytes.length) {
            throw new IOException("不能完全讀取文件");
        }
        inputStream.close();
        String encodedFileString = Base64.getEncoder().encodeToString(bytes);
        return encodedFileString;
    }

用Base64将Stri

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值