import java.io.FileReader;
import java.io.IOException;
public class FileReaderExample {
public static void main(String[] args) {
// 定义文件路径
String filePath = "example.txt";
// 创建FileReader对象
try (FileReader fileReader = new FileReader(filePath)) {
int character;
// 逐个字符读取文件内容
while ((character = fileReader.read()) != -1) {
System.out.print((char) character);
}
} catch (IOException e) {
// 捕获并处理IO异常
e.printStackTrace();
}
}
}
import java.io.FileReader; 和 import java.io.IOException;,用于文件读取和处理可能的IO异常。String filePath = "example.txt";,指定要读取的文件路径。try-with-resources语句创建FileReader对象,确保资源在使用后自动关闭。fileReader.read()方法逐个字符读取文件内容,并将其打印到控制台。当到达文件末尾时,read()方法返回-1。catch块捕获并处理可能发生的IOException异常。上一篇:java 获取服务器ip
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站