import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFileExample {
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 用于处理可能的 I/O 错误。String filePath = "example.txt"; 指定了要读取的文件路径。你可以根据需要修改这个路径。BufferedReader 在使用完毕后自动关闭,避免资源泄漏。br.readLine() 方法逐行读取文件内容,并将其打印到控制台。IOException,以确保程序不会因 I/O 错误而崩溃。上一篇:java 转大写
下一篇:java bitset
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站