java如何输出txt文件

java如何输出txt文件

作者:Elara发布时间:2026-02-05阅读时长:0 分钟阅读次数:2

用户关注问题

Q
如何在Java中读取并打印txt文件内容?

我想用Java读取一个txt文件的内容并输出到控制台,该怎么做?

A

使用BufferedReader读取txt文件内容

在Java中,可以使用BufferedReader结合FileReader来读取txt文件。通过循环调用readLine()方法逐行读取文件内容,然后使用System.out.println()输出即可。例如:

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();
}

Q
怎样用Java写入文本内容到txt文件?

我想把一段文字写进txt文件,在Java中该如何操作?

A

利用BufferedWriter写入文本到txt文件

可以在Java中使用BufferedWriter类来写文本文件。创建BufferedWriter对象时传入FileWriter,并使用write()方法写入内容。操作完成后别忘了关闭流,比如:

try (BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"))) {
bw.write("这是要写入txt文件的内容。");
} catch (IOException e) {
e.printStackTrace();
}

Q
Java中有没有更简单的方式写入和读取txt文件?

除了使用BufferedReader和BufferedWriter,Java有没有更简便的方法来读写txt文件?

A

使用java.nio.file包简化读写文件操作

Java 7及以上版本提供了java.nio.file.Files类,可以方便地读取和写入文件内容。读取可以用Files.readAllLines(),写入可以用Files.write(),例如:

List lines = Files.readAllLines(Paths.get("file.txt"));
lines.forEach(System.out::println);

List content = Arrays.asList("第一行", "第二行");
Files.write(Paths.get("output.txt"), content);