java InputStream转string

本文介绍了三种常用的将InputStream转换为String的方法,包括直接读取字节、使用BufferedReader逐行读取以及使用Apache IOUtils工具类;同时也提供了两种将String转换为InputStream的方式。

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

常用的几种InputStream 和String 互相转换的方法。

1.

            InputStream inputStream = resource.getInputStream();
			byte[] bytes = new byte[0];
			bytes = new byte[inputStream.available()];
			inputStream.read(bytes);
            System.out.println("输出"+bytes );

2.(个人建议这种)

			InputStream inputStream = resource.getInputStream();
			
			StringBuilder sb = new StringBuilder();
			String line;

			BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
			while ((line = br.readLine()) != null) {
			    sb.append(line);
			}
			
			String str = sb.toString();
			System.out.println("输出"+str );

3. Apache (方便)

String str = IOUtils.toString(inputStream, "utf-8");

 

将String转换为InputStream

1.

InputStream is = new ByteArrayInputStream(str.getBytes());

2.Apache

InputStream targetStream = IOUtils.toInputStream(str, StandardCharsets.UTF_8.name());

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值