InputStream转为String的两种方式
一. 背景在项目开发过程中,经常会从某种存储介质中读取到InputStream流中,之后我们需要将InputStream流转换为String字符串的形式,然后使用这个String串进行后面的操作。经过查询,整理了如下两种方式。二. InputStream转为String的方式1. 使用 inputStream.read 和 ByteArrayOutputStream优点:速度快2. 使用 Inpu
一. 背景
在项目开发过程中,经常会从某种存储介质中读取到InputStream流中,之后我们需要将InputStream流转换为String字符串的形式,然后使用这个String串进行后面的操作。经过查询,整理了如下两种方式。
二. InputStream转为String的方式
1. 使用 inputStream.read 和 ByteArrayOutputStream
优点:速度快
public static String getStringByInputStream_1(InputStream inputStream){
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
byte[] b = new byte[10240];
int n;
while ((n = inputStream.read(b)) != -1) {
outputStream.write(b, 0, n);
}
} catch (Exception e) {
try {
inputStream.close();
outputStream.close();
} catch (Exception e1) {
}
}
return outputStream.toString();
}
2. 使用 InputStreamReader 和 BufferedReader
public static String getStringByInputStream_2(InputStream inputStream){
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
try {
StringBuilder result = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
result.append(line);
}
return result.toString();
} catch (Exception e) {
try {
inputStream.close();
bufferedReader.close();
} catch (Exception e1) {
}
}
return null;
}
三. 参考文献
11种将InputStream转换成String的方法以及性能分析
————————————————
版权声明:本文为CSDN博主「zijikanwa」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/zijikanwa/article/details/108850332

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。
更多推荐
所有评论(0)