【发布时间】:2020-09-10 10:38:21
【问题描述】:
我想在一个文本文件中写入 100 万行。
当我使用没有try-with-resource 样式的 FileWriter(不释放资源)时,我发现它在 998976 左右停止。
...
998968
998969
998970
998971
998972
998973
998974
998975
998976
9
@Test
void writeTooLargeFileThisIsBad() throws IOException {
File newFile = new File("src/test/resources/targets/large.csv");
if (!newFile.exists()) newFile.createNewFile();
FileWriter writer = new FileWriter("src/test/resources/targets/large.csv", StandardCharsets.UTF_8);
for (int i = 1; i < 1000000; i++) {
writer.write(String.valueOf(i));
writer.write(System.lineSeparator());
}
}
但是当我尝试使用资源时,它会正常完成。 (达到999999)
两者都很快。
为什么?
@Test
void writeTooLargeFileThisIsGood() throws IOException {
File newFile = new File("src/test/resources/targets/large.csv");
if (!newFile.exists()) newFile.createNewFile();
try (FileWriter writer = new FileWriter("src/test/resources/targets/large.csv", StandardCharsets.UTF_8)) {
for (int i = 1; i < 1000000; i++) {
writer.write(String.valueOf(i));
writer.write(System.lineSeparator());
}
} catch (Exception e) {
e.printStackTrace();
}
}
【问题讨论】:
-
可能是因为writer最后没有关闭,所以最后的输出行可能没有被flush并输出到文件中。不过只是猜测。
标签: java resources filewriter try-with-resources