Java读取文件为字符串方法

方法一:使用Files工具类

  • java.nio.file.Files工具类,不依赖三方组件
  • Path.of方法在jdk11才支持
public String fileToString(String path) throws IOException {return Files.readString(Path.of(path));}

方法二:使用字符流FileReader

public String fileToString2(String path) throws IOException {FileReader reader = new FileReader(new File(path));StringBuilder stringBuilder = new StringBuilder();char[] buffer = new char[10];int size;while ((size = reader.read(buffer)) != -1) {stringBuilder.append(buffer, 0, size);}return stringBuilder.toString();}

常见字符流和字节流

方法三:使用Apache的Commons Io组件工具类

<dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.11.0</version></dependency>
public String fileToString(String path) throws IOException {return FileUtils.readFileToString(new File(path), StandardCharsets.UTF_8);}