【发布时间】: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