import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadTxtFile {
public static void main(String[] args) {
// 定义文件路径
String filePath = "example.txt";
// 使用try-with-resources确保资源关闭
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
String line;
// 逐行读取文件内容并打印
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
// 捕获并处理IO异常
e.printStackTrace();
}
}
}
BufferedReader 和 FileReader 是用于读取文件的类,IOException 用于处理可能发生的输入输出异常。String filePath = "example.txt"; 指定了要读取的文件路径。请确保文件路径正确。try-with-resources:这是一种确保资源(如文件流)在使用完毕后自动关闭的方式,避免资源泄露。BufferedReader 的 readLine() 方法逐行读取文件内容,并使用 System.out.println() 打印每一行。IOException 异常,确保程序不会因文件读取错误而崩溃。上一篇:java new file
下一篇:java日期格式
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站