【问题标题】:Close file for reading before start writing在开始写入之前关闭文件以进行读取
【发布时间】:2017-09-26 07:22:50
【问题描述】:

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

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

【问题讨论】:

  • 是的,确实如此。这是它唯一做的事情。奇怪的问题。

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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2017-05-28
    • 1970-01-01
    • 2017-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-08
    相关资源
    最近更新 更多