Groovy File.getText() - 我必须关闭一些东西吗?

时间:2014-04-29 08:32:51

标签: file groovy filereader

如果我在groovy中使用File.getText()方法

newFile().textnewFile().getText()

我是否必须执行一些闭包语句才能关闭使用过的文件阅读器,或者方法是否自行完成?

1 个答案:

答案 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