在java中如何将一个输入了 InputStream转为一个字符串String?
在java中如何将一个输入了 InputStream转为一个字符串String?
回答:
将InputStream转换为字符串的方法:
使用IOUtils.toString(Apache Utils)
String result = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
使用CharStreams(Guava)
String result = CharStreams.toString(new InputStreamReader( inputStream, Charsets.UTF_8));
使用Scanner(JDK)
Scanner s = new Scanner(inputStream).useDelimiter("\\A");String result = s.hasNext() ? s.next() : "";
使用Stream API(Java 8)。警告:此解决方案会将不同的换行符(如\r\n)转换为\n。
String result = new BufferedReader(new InputStreamReader(inputStream)) .lines().collect(Collectors.joining("\n"));
使用并行流API(Java 8)。警告:此解决方案会将不同的换行符(如\r\n)转换为\n。
String result = new BufferedReader(new InputStreamReader(inputStream)).lines() .parallel().collect(Collectors.joining("\n"));
使用InputStreamReader和StringBuilder(JDK)
final int bufferSize = 1024;final char[] buffer = new char[bufferSize];
final StringBuilder out = new StringBuilder();
Reader in = new InputStreamReader(stream, StandardCharsets.UTF_8);
int charsRead;
while((charsRead = in.read(buffer, 0, buffer.length)) > 0) {
out.append(buffer, 0, charsRead);
}
return out.toString();
使用StringWriter和IOUtils.copy(Apache Commons)
StringWriter writer = new StringWriter();IOUtils.copy(inputStream, writer, "UTF-8");
return writer.toString();
使用ByteArrayOutputStream和inputStream.read(JDK)
ByteArrayOutputStream result = new ByteArrayOutputStream();byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) != -1) {
result.write(buffer, 0, length);
}
// StandardCharsets.UTF_8.name() > JDK 7
return result.toString("UTF-8");
使用BufferedReader(JDK)。警告:此解决方案将不同的换行符(如\n\r)转换为line.separator系统属性(例如,在Windows中转换为“ \ r \ n”)。
String newLine = System.getProperty("line.separator");BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder result = new StringBuilder();
boolean flag = false;
for (String line; (line = reader.readLine()) != null; ) {
result.append(flag? newLine: "").append(line);
flag = true;
}
return result.toString();
使用BufferedInputStream和ByteArrayOutputStream(JDK)
BufferedInputStream bis = new BufferedInputStream(inputStream);ByteArrayOutputStream buf = new ByteArrayOutputStream();
int result = bis.read();
while(result != -1) {
buf.write((byte) result);
result = bis.read();
}
// StandardCharsets.UTF_8.name() > JDK 7
return buf.toString("UTF-8");
使用inputStream.read()和StringBuilder(JDK)。警告:此解决方案存在Unicode问题,例如俄语文本(仅适用于非Unicode文本)
int ch;StringBuilder sb = new StringBuilder();
while((ch = inputStream.read()) != -1)
sb.append((char)ch);
reset();
return sb.toString();
以上是 在java中如何将一个输入了 InputStream转为一个字符串String? 的全部内容, 来源链接: utcz.com/qa/432578.html