如下, 一共存在11种实现方式及其对应的性能测试结果:
1. 使用IOUtils.toString (Apache Utils)
String result = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
2. 使用CharStreams (guava)
String result = CharStreams.toString(new InputStreamReader(inputStream, Charsets.UTF_8));
3. 使用Scanner (JDK)
Scanner s = new Scanner(inputStream).useDelimiter("\\A");
String result = s.hasNext() ? s.next() : "";
4. 使用Stream Api (Java 8). 提醒: 这种方式会将不同的换行符 (比如\r\n) 都替换为 \n.
String result = new BufferedReader(new InputStreamReader(inputStream))
.lines().collect(Collectors.joining("\n"));
5. 使用parallel Stream Api (Java 8). 提醒: 这种方式会将不同的换行符 (比如\r\n) 都替换为 \n.
String result = new BufferedReader(new InputStreamReader(inputStream))
.lines().parallel().collect(Collectors.joining("\n"));
6. 使用InputStreamReader 和StringBuilder (JDK)
final int bufferSize = 1024;
final char[] buffer = new char[bufferSize];
final StringBuilder out = new StringBuilder();
Reader in = new InputStreamReader(inputStream, "UTF-8");
for (; ; ) {
int rsz = in.read(buffer, 0, buffer.length);
if (rsz < 0)
break;
out.append(buffer, 0, rsz);
}
return out.toString();
7. 使用StringWriter 和 IOUtils.copy (Apache Commons)
StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, "UTF-8");
return writer.toString();
8. 使用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);
}
return result.toString("UTF-8");
9. 使用BufferedReader (JDK). 提醒: 这种方式会将不同的换行符 (比如\r\n) 都替换为当前系统的换行符(例如, 在windows下是"\r\n").
String newLine = System.getProperty("line.separator");
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder result = new StringBuilder();
String line; boolean flag = false;
while ((line = reader.readLine()) != null) {
result.append(flag? newLine: "").append(line);
flag = true;
}
return result.toString();
10. 使用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();
}
return buf.toString();
11. 使用 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();
网友评论