2017-09-26 97 views
-1

我寫了一個方法來替換文件中的一些行(這不是這個問題的目的)。一切工作正常,但我想知道,如果文件關閉閱讀時,我開始寫作。我想確保我的解決方案是安全的。這就是我所做的:在開始寫作之前關閉文件

private void replaceCodeInTranslationFile(File file, String code) { 
    if (file.exists()) { 
    try (Stream<String> lines = Files.lines(Paths.get(file.getAbsolutePath()), Charset.defaultCharset())) { 
     String output = this.getLinesWithUpdatedCode(lines, code); 
     this.replaceFileWithContent(file, output); // is it safe? 
    } catch (IOException e) { 
     throw new UncheckedIOException(e); 
    } 
    } 
} 

方法replaceFileWithContent()看起來是這樣的:

private void replaceFileWithContent(File file, String content) throws IOException { 
    try (FileOutputStream fileOut = new FileOutputStream(file.getAbsolutePath())) { 
    fileOut.write(content.getBytes(Charset.defaultCharset())); 
    } 
} 

我認爲try-with-resources在聲明的最後關閉的資源,因此,這段代碼可以是問題的潛在來源。我對麼?

+0

是的,它的確如此。這是它只做的*事情。奇怪的問題。 – EJP

回答