Recently I am doing a code review, the code is like this:
File j = new File(aFile);
System.out.println(j.length());
BufferedReader fileReader = new BufferedReader(new FileReader(j));
BufferedWriter fileWriter = new BufferedWriter(new FileWriter(aFile.getPath());
System.out.println(j.length());
I have two questions:
Is
j
a duplicate ofaFile
, because I have seen other huge methods for copying files, like here.The first
System.out.println()
prints32
and the second, after creating a file reader, prints0
. So, why are the contents getting deleted? Could someone explain what's happening here?
I put those System.out.println()
statements to check if the file is empty or not.
Solution:
After Reading through the answers, I think I found what's wrong with the code. If j
is just a reference, then the fileWriter
is trying to write into the same file and it is cyclic. Am I right here?
EDIT: This is not a duplicate of suggested question, as the whole confusion was thinking that the j
is clone or duplicate of aFile
.