Reputation: 334
So I have this piece of code that is supposed to swap the old file with new file (the old file already exists, and the new file gets generated in different method of the same class, but I tested it and it gets generated properly so the bug is not in the file), but for some reason, the file does not get renamed and the wrong one gets deleted. Been stuck with this over a hour now, any feedback is welcome.
public static void replaceAndDelete() {
String pathOLD = System.getProperty("user.home");
pathOLD = pathOLD+"\\cd.txt";
File fileOLD = new File(pathOLD);
String pathNEW = System.getProperty("user.home");
pathNEW = pathNEW+"\\temp.txt";
File fileNEW = new File (pathNEW);
fileNEW.renameTo(fileOLD);
fileOLD.delete();
}
Upvotes: 0
Views: 66
Reputation: 131
You are renaming fileNEW
to fileOLD
and then deleting the fileOLD
. That means you're deleting the path, not the "virtual file" in the JVM memory.
The final code with some edit was:
String pathOLD = "C:\\test\\old.txt";
String pathNEW = "C:\\test\\new.txt";
File fileOLD = new File(pathOLD);
File fileNEW = new File (pathNEW);
fileOLD.delete();
fileNEW.renameTo(fileOLD);
Don't forget you're deleting the old one and renaming the new with the old's name. That means you should check the inside of the file, because I was also thinking it was deleting the wrong file while it was simply deleting and renaming correcly.
Upvotes: 1
Reputation: 12214
It looks like these lines are not in the order you want:
fileNEW.renameTo(fileOLD);
fileOLD.delete();
Upvotes: 0