为什么文件重命名失败?
我的操作系统是 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");
}
}
}
最佳答案
失败是因为您的时间戳字符串包含 Windows 操作系统不允许的 :
字符。替换它们,它将起作用。
_dateTimeNowStr = _dateTimeNowStr.replace(":", "_");
关于java - 文件重命名失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38739768/