gpt4 book ai didi

Java:引用和 GC

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:14:51 24 4
gpt4 key购买 nike

我是 Java 编程的新手,我以某种方式了解引用和垃圾收集器的工作原理,但我需要一些建议。

如果(例如)我需要从文件中读取,并且我正在使用循环遍历每个文件并从中读取文本,我是否应该避免做类似的事情:

(br 是 BufferedReader 的一个实例)

br = new BufferedReader(new FileReader("filePath"));

基本上,每次循环执行时,br 都会引用 BufferedReader 的新对象。这是错误的做法吗?如果是,我可以做些什么来让它更有效地工作?

提前感谢您提供的任何帮助。

完整代码:

  public int kerko(String folderName, String wantedWord) throws IOException{
File file = new File(folderName);

int count = 0;
if(file.isDirectory()){
File[] files = file.listFiles();
for(File f: files){
if(f.isFile() && f.getName().endsWith(".txt")){
br = new BufferedReader(new FileReader(f.getAbsolutePath()));
String line = br.readLine();
while(line != null){
if(line.toLowerCase().contains(wantedWord)){
count++;
}

line = br.readLine();
}
br.close();
}
count += kerko(f.getAbsolutePath(), wantedWord);
}
}
return count;
}

最佳答案

用这种方式实例化BufferedReader和FileReader是可以的。

离开 { } block 后,这些对象将无法访问,稍后 GC 将收集它们。

关于Java:引用和 GC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37470716/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com