2017-10-18 4 views
1

のファイルリソース私はグルーヴィーでAutoClosable InputStreamを実装しようとしていますが、以下のスニペットの構文を認識することができない、私はので、代わりに私がnew File(relativePath).getText()を使用し、私の古いプロジェクトのJavaクラスからAutoclosable、Groovyの

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

を取っていますうまくいく。

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 
} 

私は2つの質問

  1. を持っているが、私はそれがドキュメントだ見つけることができますAutoClosableに似new File(relativePath).getText()オートリリースファイルリソースを、していますか?
  2. の構文がgroovyで動作しないのはなぜですか?

なGroovy:2.4.7、 JVM:1.8.0_111

+2

File.getText()グルーヴィーな強化は、最終的に試して実装し、ストリームを閉じます。 File.getText()は[IOGroovyMethods]を呼び出します(http://docs.groovy-lang.org/2.4.3/html/api/org/codehaus/groovy/runtime/IOGroovyMethods.html#getText(java.io.Reader) )このメソッドは "このメソッドが戻る前に、リーダーが閉じている"と文書化します。 – JasonM1

答えて

4

のJava 7でのtry-とリソース構文は直接Groovyでサポートされていませんが、同等の構文はのための同様の方法で(もwithCloseableメソッドを使用して参照してくださいですストリーム、リーダ)とコードのクロージャブロックがあります。 Groovy enhancements to File I/Oと関連するtutorialを確認してください。

例:質問の後半部分について

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

、File.getText()Groovyの強化は、try-ついに実装し、ストリームを閉じます。

これは、上記のコードと同じことを行います

text = new File(relativePath).getText() 
+0

'toString(istream)'は推奨されていません – Ricky