方法1
纯原生方法,通过BufferedReader
类读取:
public static String read1(InputStream inputStream) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuffer sb = new StringBuffer();
String line = bufferedReader.readLine();
while (line != null) {
sb.append(line).append("\n");
line = bufferedReader.readLine();
}
return sb.toString();
}
方法2
使用IOUtils
工具类,在pom.xml文件中引入依赖:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.2</version>
</dependency>
读取文件内容方法封装:
public static String read2(InputStream inputStream) throws IOException {
List<String> lines = org.apache.commons.io.IOUtils.readLines(inputStream);
return String.join("\n", lines);
}