If I use the File.getText() method in groovy

newFile().text or newFile().getText()

do I have to execute some closure statements to close the used file reader or will the method do it by itself?

有帮助吗?

解决方案

It will do it by itself.

Calling 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));
}

Which as you can see 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();
}

Which as you can see, closes the Reader when done

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top