Search code examples
javapointersreferencefilewriter

FileWriter object reference not being overwritten as expected


I was working with a fellow peer on a simple coding exercise and we stumbled across this issue.

The program requirements outlined that if the third command line argument was "a", the output file should be appended to, not replaced.

So, he had code something like this:

import java.io.FileWriter;
import java.io.IOException;

public class MyFileWriter {
   public static void main(String[] args) {
       //...
      try {
         FileWriter fw = new FileWriter("testfile");

         if(args[2].equals("a")) {
            fw = new FileWriter("testfile", true);
         } 
         else if(args[2].equals("r")) {
            fw = new FileWriter("testfile");
         }
      } 
      catch(IOException e) {
         System.out.println(e.getMessage());
      }

   }
}

I know that initializing FileWriter before either of the if statements is redundant, but that's how it was set up. We ran it with the third command line argument being "a", and that if statement ran successfully. However, the FileWriter object was not appending to the file as was expected.

We changed the initial declaration of the FileWriter to the following:

FileWriter fw = null;

And then it worked. I figured it had to be some kind of reference or pointer issue, but why? Theoretically, the assignment operator should overwrite the value of whatever the thing points to, so even though initializing it to begin with is redundant, it should just overwrite the object entirely.

Anyone know why this was an issue? I'm just curious.


Solution

  • I figured it had to be some kind of reference or pointer issue, but why?

    No, its a matter of your code flow and how you call the FileWriter() constructor.

    The first call to FileWriter() in

    try {
         FileWriter fw = new FileWriter("testfile");
         ....
    

    already overwrites and clears the file, before you later on create another FileWriter which was intended to append to it:

    ...
    if(args[2].equals("a")) {
        fw = new FileWriter("testfile", true);   // here, "testfile" was already overwritten
    }
    ...
    

    Hence, effectively you are appending to an empty file.

    Keep in mind that Constructors can contain any kind of program code. You do not even necessarily have to assign the "result" of the constructor call to a variable - the following would have the same effect of overwriting the file:

    ...
    new FileWriter("testfile");
    ....