在开始写作之前关闭文件
问题描述:
我写了一个方法来替换文件中的一些行(这不是这个问题的目的)。一切工作正常,但我想知道,如果文件关闭阅读时,我开始写作。我想确保我的解决方案是安全的。这就是我所做的:在开始写作之前关闭文件
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
在声明的最后关闭的资源,因此,这段代码可以是问题的潜在来源。我对么?
答
读取/写入锁定实现可能有助于确保线程安全操作的这种场景。 参考http://tutorials.jenkov.com/java-concurrency/read-write-locks.html更多..
是的,它的确如此。这是它只做的*事情。奇怪的问题。 – EJP