java读取txt文件的方法有哪些
- 使用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();
}
- 使用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();
}
- 使用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();
}
版权声明
本文仅代表作者观点,不代表米安网络立场。
上一篇:python的断言方法有哪些 下一篇:vue表单数据验证怎么实现
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。