Java - renameTo 方法不起作用

发布于 2024-09-14 06:22:46 字数 829 浏览 4 评论 0原文

我尝试在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

一场春暖 2024-09-21 06:22:46

您无法重命名或删除 Windows 认为已打开的文件。

You cannot rename or delete a file which Windows consider to be open.

離殇 2024-09-21 06:22:46

您需要先创建子文件夹,然后再将文件移入其中(取消注释 subFolder.mkdir();)

You need to create the subfolder before you move the file into it (uncomment subFolder.mkdir();)

挖个坑埋了你 2024-09-21 06:22:46

我建议您检查是否存在。 公共布尔存在()

更多信息请参见此处

I would recommend you to check for exists. public boolean exists()

More here

坏尐絯 2024-09-21 06:22:46

如果我在行中发表评论,它会起作用

subFolder.mkdir();

it works, if I comment in the line

subFolder.mkdir();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文