如果我在groovy 中使用File.getText()
方法
newFile().text
或newFile().getText()
我必须执行一些闭包语句来关闭使用过的文件读取器吗?还是该方法会自己完成?
它将自己完成。
调用new File( 'a.txt' ).text
将调用ResourceGroovyMethods.getText( File )
public static String getText(File file, String charset) throws IOException {
return IOGroovyMethods.getText(newReader(file, charset));
}
正如你所看到的,它调用IOGroovyMethods.getText( BufferedReader )
:
public static String getText(BufferedReader reader) throws IOException {
StringBuilder answer = new StringBuilder();
// reading the content of the file within a char buffer
// allow to keep the correct line endings
char[] charBuffer = new char[8192];
int nbCharRead /* = 0*/;
try {
while ((nbCharRead = reader.read(charBuffer)) != -1) {
// appends buffer
answer.append(charBuffer, 0, nbCharRead);
}
Reader temp = reader;
reader = null;
temp.close();
} finally {
closeWithWarning(reader);
}
return answer.toString();
}
正如您所看到的,完成时关闭阅读器