首页javareadJava I/O - 如何读取完整的文件内容到字符串

Java I/O - 如何读取完整的文件内容到字符串

我们想知道如何读取完整的文件内容到字符串。
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;


public class Main{
  /**
   * Converts a file to a string
   * @param f The file
   * @return The string
   * @throws IOException Thrown in any IOException occurs
   */
  public static String fileToString(File f) throws IOException {
      ArrayList<String> list = new ArrayList<>(Files.readAllLines(f.toPath()));
      StringBuilder builder = new StringBuilder();
      list.forEach(builder::append);
      return builder.toString();
  }
}