【问题标题】:File rename fails文件重命名失败
【发布时间】:2016-12-08 22:47:05
【问题描述】:

为什么文件重命名失败?

我的操作系统是 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");
          }
    }
}

【问题讨论】:

  • “失败”是什么意思?你得到一个错误还是什么?

标签: java file rename file-rename


【解决方案1】:

它失败是因为您的时间戳字符串包含 Windows 操作系统不允许的 : 字符。替换它们就可以了。

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

【讨论】:

    猜你喜欢
    • 2018-10-16
    • 1970-01-01
    • 2012-08-06
    • 1970-01-01
    • 2014-07-27
    • 2013-12-29
    • 1970-01-01
    • 2014-06-24
    • 1970-01-01
    相关资源
    最近更新 更多