Search code examples
javafilerenamefile-rename

File rename fails


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");
          }
    }
}

Solution

  • 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(":", "_");