0

I want to write 1 million lines to a text file.

When I use FileWriter without try-with-resource style(not releasing resources), I found it stops at around 998976 and so.

...
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());
        }
    }

But when I do with try with resource, it completes normally. (It reaches 999999)

Both very quick.

Why?

    @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();
        }
    }
WesternGun
  • 11,303
  • 6
  • 88
  • 157
  • It's probably because the writer doesn't get closed in the end, so the final lines of output may not be flushed and output to the file. Just a guess though. – maloomeister Sep 10 '20 at 10:41

1 Answers1

3

That's because you are not calling close() method on the writer instance - the writer has some buffer defined able to store quite big amount of unwritten data

When you are using try-with-resource approach the close() is being called automatically so every data is being flushed properly


Read more here:

m.antkowicz
  • 13,268
  • 18
  • 37