2017-09-26 98 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

回答