在开始撰写之前关闭文件进行阅读

时间:2017-09-26 07:22:51

标签: java file file-writing try-with-resources

我写了一个替换文件中某些行的方法(这不是这个问题的目的)。一切正常,但我想知道当我开始写作时文件是否关闭阅读。我想确保我的解决方案是安全的。这就是我所做的:

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会在语句结束时关闭资源,因此这段代码可能是问题的根源。我是对的吗?

1 个答案:

答案 0 :(得分:0)

读/写锁实现可能有助于此类场景以确保线程安全操作。 请参阅此http://tutorials.jenkov.com/java-concurrency/read-write-locks.html了解更多信息..

相关问题