我为沿文件行迭代的迭代器编写了以下类。
import java.io.*;
import java.util.Iterator;
public class FileIterator implements Iterator<String> {
private BufferedReader reader;
public FileIterator(String filename) {
this.reader = getBufferedReader(filename);
}
private static BufferedReader getBufferedReader(String filename) {
File file = new File(filename);
if(file.exists()) {
try {
return new BufferedReader(new InputStreamReader(
new FileInputStream(new File(filename)),"UTF-8"));
} catch (Exception e) {
e.printStackTrace();
return null;
}
} else {
System.out.println(filename + " is not there");
return null;
}
}
public boolean hasNext() {
try {
return reader.ready();
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public String next() {
try {
return reader.readLine();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public void remove() {}
}
现在我的问题有点幼稚。一旦不再使用迭代器,阅读器是否会关闭,什么时候 GC 会处理它?如果我手动关闭阅读器,课程会改善吗?也许作为 hasNext() 方法的副作用:
public boolean hasNext() {
try {
if(reader.ready()) return true;
else {
reader.close();
return false;
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
谢谢!