import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class FileReaderExample {
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 在使用完毕后自动关闭,避免资源泄露。while ((line = br.readLine()) != null) 循环逐行读取文件内容,并打印每一行。IOException,以确保程序不会因文件读取错误而崩溃。如果需要进一步的帮助或有其他问题,请随时告知!
上一篇:java arraylist
下一篇:java map 遍历
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站