Java

java读取txt文件的方法有哪些

小亿
94
2023-06-26 13:11:26
栏目: 编程语言

  1. 使用FileReader和BufferedReader类:
try {
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();
} catch (IOException e) {
e.printStackTrace();
}
  1. 使用Scanner类:
try {
File file = new File("filename.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
  1. 使用Files类:
try {
Path path = Paths.get("filename.txt");
List<String> lines = Files.readAllLines(path);
for (String line : lines) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}

0
看了该问题的人还看了