<span style="font-size:18px;">import java.io.File;
import java.io.FileReader;
import java.io.IOException;
//try-with-resources
public class FileXieRuTryWithResources {
public static void main(String[] args) {
File file = new File("./bcd.txt");// 一个点 表示当前根目录
try (FileReader fileReader = new FileReader(file);) {
char[] chr = new char[(int) (file.length())];
int len = -1;
while ((len = fileReader.read(chr)) != -1) {
String string = new String(chr, 0, len);
System.out.println(string);
}
} catch (IOException e) {
}
}
}</span>
try- with -resoures用法:
try(//需要释放资源的代码){
//具体执行的代码
}cathch (IOException e){
}
本文提供了一个使用Java进行文件读取的示例代码,展示了如何利用try-with-resources语句来自动关闭FileReader对象,从而简化了资源管理并提高了代码的可读性和安全性。
6092

被折叠的 条评论
为什么被折叠?



