import java.io.*;
public class ReadFileExample {
public static void main(String[] args) {
// 文件路径
String filePath = "example.txt";
File file = new File(filePath);
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
// 逐行读取文件内容并打印
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
java.io.* 包含了处理文件输入输出的类。String filePath = "example.txt"; 指定要读取的文件路径。File 对象:File file = new File(filePath); 创建一个表示文件的 File 对象。BufferedReader 和 FileReader:BufferedReader 提供了高效的字符读取功能,FileReader 用于从文件中读取字符。while ((line = br.readLine()) != null) 循环逐行读取文件内容,并使用 System.out.println(line); 打印每一行。try-catch 块捕获可能发生的 IOException 异常,并打印堆栈跟踪信息。如果你需要更详细的解释或其他功能,请告诉我!
上一篇:java怎么连接mysql数据库
下一篇:java编程
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站