Reputation: 626
Why file rename fails?
My OS is Windows 7 and folder C:/test/dfhsdfhs
exists in file system.
My code:
String path = "C:/test/dfhsdfhs/test2.txt";
boolean hasDeleteFolder = true;
File delFile = new File(path);
if (delFile.exists()) {
if (hasDeleteFolder == true) {
Date dateTimeNow = new Date();
String _dateTimeNowStr = dateTimeNow.toString();
_dateTimeNowStr = _dateTimeNowStr.replace(" ", "_");
File timeStampFile = new File (delFile.getAbsolutePath() + "_" + _dateTimeNowStr + "." + FilenameUtils.getExtension(delFile.getName()));
if (delFile.renameTo(timeStampFile)) {
System.out.println("renamed");
} else {
System.out.println("Error");
}
}
}
Upvotes: 3
Views: 147
Reputation: 4039
It fails because your timestamp string contains :
characters which is not allowed with windows operating system. Replace them and it will work.
_dateTimeNowStr = _dateTimeNowStr.replace(":", "_");
Upvotes: 6