方法1

纯原生方法,通过BufferedReader类读取:

  1. public static String read1(InputStream inputStream) throws IOException {
  2. BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
  3. StringBuffer sb = new StringBuffer();
  4. String line = bufferedReader.readLine();
  5. while (line != null) {
  6. sb.append(line).append("\n");
  7. line = bufferedReader.readLine();
  8. }
  9. return sb.toString();
  10. }

方法2

使用IOUtils工具类,在pom.xml文件中引入依赖:

  1. <dependency>
  2. <groupId>commons-io</groupId>
  3. <artifactId>commons-io</artifactId>
  4. <version>2.2</version>
  5. </dependency>

读取文件内容方法封装:

  1. public static String read2(InputStream inputStream) throws IOException {
  2. List<String> lines = org.apache.commons.io.IOUtils.readLines(inputStream);
  3. return String.join("\n", lines);
  4. }