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.