可自动关闭,Groovy中的文件资源

z18hc3ub  于 2022-11-01  发布在  其他
关注(0)|答案(2)|浏览(169)

我尝试在groovy中实现AutoClosable InputStream,但是它无法识别下面代码片段的语法,该代码片段是我从旧项目的Java类中获取的

try (InputStream istream = new FileInputStream(new File(relativePath))) {
    return IOUtils.toString(istream));
} catch (IOException e) {
    e.printStackTrace();
}

因此,我使用了new File(relativePath).getText(),它很有效。

def static getTemplateAsString(def relativePath) {
    /*try (InputStream istream = new FileInputStream(new File(relativePath))) {
        return IOUtils.toString(istream));
    } catch (IOException e) {
        e.printStackTrace();
    }*/
    try {
        return new File(relativePath).getText()
    } catch (FileNotFoundException fnfe) {
        fnfe.printStackTrace()
    } catch (IOException ioe) {
        ioe.printStackTrace()
    } catch (Exception e) {
        e.printStackTrace()
    }
    return null
}

我有两个问题

  1. new File(relativePath).getText()是否自动释放与AutoClosable类似的文件资源,我在哪里可以找到它的文档?
    1.为什么try (InputStream istream = new FileInputStream(new File(relativePath)))语法在groovy中不起作用?
    Groovy:2.4.7,JVM:1.8.0_111版本
brccelvz

brccelvz1#

Groovy不直接支持Java 7中引入的try-with-resource语法,但等效的语法使用了 withCloseable 方法(对于流和读取器也有类似的方法)和一个闭包代码块。

范例:

String text = null
new File(relativePath).withInputStream { istream ->
    text = IOUtils.toString(istream);
} catch (IOException e) {
    e.printStackTrace();
}
return text

对于问题的第二部分,File.getText()groovy增强实现了一个try-finally并关闭流。
这与上面的代码执行相同的操作:

text = new File(relativePath).getText()
tp5buhyn

tp5buhyn2#

Groovy的try-with-resource习惯用法是withXxx方法。

new File(baseDir,'haiku.txt').withInputStream { stream ->
    // do something ...
}

请访问http://groovy-lang.org/groovy-dev-kit.html#_working_with_io

相关问题