11分钟掌握Java中string和InputStream的转换


本人博客: https://blog.onfree.cn (●ˇ∀ˇ●)

11分钟掌握Java中string和InputStream的转换

相信奇迹的人本身就和奇迹一样了不起啊


1、InputStream转化为String

1.1 JDK原生提供
方法一:
byte[] bytes = new byte[0];
bytes = new byte[inputStream.available()];
inputStream.read(bytes);
String str = new String(bytes);
方法二:
String result = new BufferedReader(new InputStreamReader(inputStream))
        .lines().collect(Collectors.joining(System.lineSeparator()));
方法三:
String result = new BufferedReader(new InputStreamReader(inputStream))
       .lines().parallel().collect(Collectors.joining(System.lineSeparator()));
方法四:
Scanner s = new Scanner(inputStream).useDelimiter("\\A");
String str = s.hasNext() ? s.next() : "";
方法五:
String resource = new Scanner(inputStream).useDelimiter("\\Z").next();
return resource;
方法六:
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();
return str;
方法七:
ByteArrayOutputStream result = new ByteArrayOutputStream();
byte[] buffer = new byte[inStream.available()];
int length;
while ((length = inputStream.read(buffer)) != -1) {
    result.write(buffer, 0, length);
}
String str = result.toString(StandardCharsets.UTF_8.name());
return str;
方法八:
BufferedInputStream bis = new BufferedInputStream(inputStream);
ByteArrayOutputStream buf = new ByteArrayOutputStream();
int result = bis.read();
while(result != -1) {
    buf.write((byte) result);
    result = bis.read();
}
String str = buf.toString();
return str;
1.2 Apache Common提供
方法九:
StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, StandardCharsets.UTF_8.name());
String str = writer.toString();
方法十:
String str = IOUtils.toString(inputStream, "utf-8");
1.3 Google Guava提供
方法十一:
String str = CharStreams.toString(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
方法十二:
String str = new String(ByteStreams.toByteArray(inputStream));

2、String转化为InputStream

2.1 JDK原生提供
InputStream is = new ByteArrayInputStream(str.getBytes());
2.2 Apache Common提供
InputStream targetStream = IOUtils.toInputStream(str, StandardCharsets.UTF_8.name());
2.3 Google Guava提供
InputStream targetStream =
        new ReaderInputStream(CharSource.wrap(str).openStream(), StandardCharsets.UTF_8.name());

本博客原文:https://blog.onfree.cn/posts/ca446a09.html
转载请申明原作者Athink,谢谢!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值