文件重命名失败

3

为什么文件重命名失败?

我的操作系统是Windows 7,文件系统中存在文件夹C:/test/dfhsdfhs

我的代码:

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

2
“失败”是什么意思?你是否收到了错误提示? - CloudPotato
1个回答

6

出现错误的原因是你的时间戳字符串中包含了:这些在Windows操作系统中不允许的字符。将它们替换掉就能解决问题了。

_dateTimeNowStr = _dateTimeNowStr.replace(":", "_");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接