java如何读取一个txt文件
读取txt文件的几种方法
Java提供了多种读取txt文件的方式,以下是几种常见的方法:

使用BufferedReader读取
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
使用Files类读取所有行
try {
List<String> lines = Files.readAllLines(Paths.get("file.txt"));
for (String line : lines) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
使用Scanner逐行读取
try (Scanner scanner = new Scanner(new File("file.txt"))) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
使用Files.readString一次性读取
try {
String content = Files.readString(Paths.get("file.txt"));
System.out.println(content);
} catch (IOException e) {
e.printStackTrace();
}
使用FileInputStream读取字节流
try (FileInputStream fis = new FileInputStream("file.txt")) {
int content;
while ((content = fis.read()) != -1) {
System.out.print((char) content);
}
} catch (IOException e) {
e.printStackTrace();
}
注意事项
文件路径可以是相对路径或绝对路径,确保文件存在且路径正确

处理文件IO操作时总是使用try-with-resources语句或手动关闭流
考虑文件编码问题,特别是非ASCII字符时,可以指定字符集
大文件建议使用流式读取而非一次性读取全部内容






