读取文本文件中所有内容,java
1、使用Files.lines() 方法,逐行读取,然后拼接
// 读取 String interfaceTxtPath="D:\\基础.postman_collection.json"; List<String> lines = Files.readAllLines(Paths.get(interfaceTxtPath), StandardCharsets.UTF_8); String content= String.join(System.lineSeparator(),lines);
2、使用BufferedReader 逐行读取,然后以字符串存储
public static void main(String[] args) throws IOException { String path = "D:\\基础.postman_collection.json"; StringBuilder contentBuilder = new StringBuilder(); try (BufferedReader br = new BufferedReader(new FileReader(path))) { String line; while ((line = br.readLine()) != null) { contentBuilder.append(line).append(System.lineSeparator()); } } catch (IOException e) { e.printStackTrace(); } String fileContent = contentBuilder.toString(); System.out.println(fileContent); }
3、使用Files.readString()