1、使用 InputStreamReader 和 StringBuilder (JDK)
public class InputStream2String {
public static void main(String[] args) {
try {
InputStream inputStream = new FileInputStream("E:/duckAndJava/IO/testFile.txt"); //路径修改为本地文件所在的位置
char[] buffer = new char[1024]; //根据需要的数组大小进行自定义
StringBuilder out = new StringBuilder();
Reader in = new InputStreamReader(inputStream, "UTF-8");
for (int numRead; (numRead = in.read(buffer, 0, buffer.length)) > 0; ) {
out.append(buffer, 0, numRead);
}
String myString = out.toString();
System.out.println("myString = " + myString);
}catch (IOException e){
e.printStackTrace();
}
}
2、使用 inputStream.read() and StringBuilder
StringBuilder sb = new StringBuilder();
for (int ch; (ch = inputStream.read()) != -1; ) {
sb.append((char) ch);
}
String myString = sb.toString();
3、使用 ByteArrayOutputStream and inputStream.read
ByteArrayOutputStream result = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
for (int length; (length = inputStream.read(buffer)) != -1; ) {
result.write(buffer, 0, length);
}
String myString = result.toString("UTF-8");
4、使用 BufferedInputStream 和 ByteArrayOutputStream
BufferedInputStream bis = new BufferedInputStream(inputStream);
ByteArrayOutputStream buf = new ByteArrayOutputStream();
for (int result = bis.read(); result != -1; result = bis.read()) {
buf.write((byte) result);
}
String myString = buf.toString("UTF-8");
5、使用 BufferedReader
String newLine = System.getProperty("line.separator");
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
StringBuilder result = new StringBuilder();
for (String line; (line = reader.readLine()) != null; ) {
if (result.length() > 0) {
result.append(newLine);
}
result.append(line);
}
String myString = result.toString();
6、使用 Stream API 或 parallel Stream API
String myString = new BufferedReader(new InputStreamReader(inputStream)).lines().collect(Collectors.joining("\n"));
或
String myString = new BufferedReader(new InputStreamReader(inputStream)).lines().parallel().collect(Collectors.joining("\n"));
7、使用 StringWriter 和IOUtils.copy (Apache Commons)
StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, "UTF-8");
return writer.toString();
甚至可以直接这样用
String result = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
8、使用CharStreams (Google Guava)
String result = CharStreams.toString(new InputStreamReader(inputStream, Charsets.UTF_8));