Java讀取文本文件的方法有以下幾種:
File file = new File("filename.txt");
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
fr.close();
File file = new File("filename.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
scanner.close();
Path path = Paths.get("filename.txt");
List<String> lines = Files.readAllLines(path);
for (String line : lines) {
System.out.println(line);
}
Path path = Paths.get("filename.txt");
BufferedReader br = Files.newBufferedReader(path);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();