如下, 一共存在11種實(shí)現(xiàn)方式及其對(duì)應(yīng)的性能測(cè)試結(jié)果:
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). 提醒: 這種方式會(huì)將不同的換行符 (比如\r\n) 都替換為 \n.
String result = new BufferedReader(new InputStreamReader(inputStream))
.lines().collect(Collectors.joining("\n"));
5. 使用parallel Stream Api (Java 8). 提醒: 這種方式會(huì)將不同的換行符 (比如\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). 提醒: 這種方式會(huì)將不同的換行符 (比如\r\n) 都替換為當(dāng)前系統(tǒng)的換行符(例如, 在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時(shí)存在問(wèn)題, 例如俄文, 僅在非Unicode字符串下工作正常.
int ch;
StringBuilder sb = new StringBuilder();
while((ch = inputStream.read()) != -1)
sb.append((char)ch);
reset();
return sb.toString();