如果我在groovy中使用File.getText()
方法
newFile().text
或newFile().getText()
我是否必须执行一些闭包语句才能关闭使用过的文件阅读器,或者方法是否自行完成?
答案 0 :(得分:2)
它会自己完成。
致电new File( 'a.txt' ).text
will call ResourceGroovyMethods.getText( File )
public static String getText(File file, String charset) throws IOException {
return IOGroovyMethods.getText(newReader(file, charset));
}
您可以看到calls 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();
}
如您所见,完成后关闭Reader