Java - renameTo 方法不起作用
我尝试在 Java 中使用 renameTo 方法,但它只返回 false 并且不移动文件。
我是不是少了一步?有没有办法找出为什么不移动文件? delete 方法也不执行任何操作。
这是我的代码,显示了我如何使用它:
private void archiveOutputFile(File outputFile) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddhhmmssS");
String timeStamp = formatter.format(new Date());
String subFolderName = "Archive" + timeStamp;
File subFolder = new File(outputFile.getParent(),subFolderName);
subFolder.mkdir();
File newFile = new File(subFolder,outputFile.getName());
//outputFile.deleteOnExit(); //Doesn't work, nor does .delete()
boolean success = outputFile.renameTo(newFile);
}
这是一些系统信息:
Java:1.6.0_21; Java HotSpot(TM) 客户端 VM 17.0-b17
系统:在 x86 上运行的 Windows XP 版本 5.1; Cp1252; en_US (nb)
I'm trying to use the renameTo method in Java but it just returns false and doesn't move the file.
Am I missing a step? Is there a way to find out why it's not moving the file? The delete method doesn't do anything either.
Here's my code showing how I'm using it:
private void archiveOutputFile(File outputFile) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddhhmmssS");
String timeStamp = formatter.format(new Date());
String subFolderName = "Archive" + timeStamp;
File subFolder = new File(outputFile.getParent(),subFolderName);
subFolder.mkdir();
File newFile = new File(subFolder,outputFile.getName());
//outputFile.deleteOnExit(); //Doesn't work, nor does .delete()
boolean success = outputFile.renameTo(newFile);
}
Here's some system info:
Java: 1.6.0_21; Java HotSpot(TM) Client VM 17.0-b17
System: Windows XP version 5.1 running on x86; Cp1252; en_US (nb)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您无法重命名或删除 Windows 认为已打开的文件。
You cannot rename or delete a file which Windows consider to be open.
您需要先创建子文件夹,然后再将文件移入其中(取消注释 subFolder.mkdir();)
You need to create the subfolder before you move the file into it (uncomment subFolder.mkdir();)
我建议您检查是否存在。
公共布尔存在()
更多信息请参见此处
I would recommend you to check for exists.
public boolean exists()
More here
如果我在行中发表评论,它会起作用
it works, if I comment in the line