Size of file goes into GB's on writing some text in it

65 views Asked by At

For learning File read and write i have written a method in which i am writing some result into a file. On running the program the file size goes into GB's and i have to stop the program in between, which i was not expecting. I am not sure what mistake i am doing. Can you please point out the mistake in it or better way of doing it.

public static void modOperation() {
    int i = Integer.MAX_VALUE;
    FileWriter fileWriter;
    try {
        fileWriter = new FileWriter("Mod.txt");
        while (i > 0) {
            boolean result = ((i-- % 3) == 0);
            fileWriter.write(" result :: " + result);
        }
        fileWriter.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
1

There are 1 answers

0
Tim Biegeleisen On BEST ANSWER

The value Integer.MAX_VALUE is 2^31 - 1 which equals 2,147,483,647. You are writing the text " result :: " plus a number on each line, which is about 20 bytes.

2,147,483,647 x 20 bytes = 42 Terabytes

So your code certainly will cause Gigabytes (and beyond) to be written.

A better solution is to give the loop an upper bound like this:

while (i < 100000) {
    boolean result = ((i-- % 3) == 0);
    fileWriter.write(" result :: " + result);
}