不使用 renameTo() 重命名文件 - Java
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2014586/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Renaming a file without using renameTo() - Java
提问by Hristo
Disregarding my last post, I've found the source of the problem. I'm using
忽略我的上一篇文章,我已经找到了问题的根源。我正在使用
a.renameTo(b)
when b doesn't exist. The reason it doesn't exist is because there is a symbolic link so if b is /usr/name/folder/file
, then b really is /mnt/MountTest
because the symlink is to that directory.
当 b 不存在时。它不存在的原因是因为有一个符号链接,所以如果 b 是/usr/name/folder/file
,那么 b 真的是/mnt/MountTest
因为符号链接是到那个目录。
So the question is, is there an alternative way to rename a file in Java using a string value? If not, how can this rename procedure be done differently?
所以问题是,有没有其他方法可以使用字符串值在 Java 中重命名文件?如果没有,这个重命名过程如何以不同的方式完成?
采纳答案by Dean J
A rename would rename it... if it were on the same filesystem.
重命名会重命名它...如果它在同一个文件系统上。
If a renameTo() fails, you'll need to copy it to the new location, then delete the original.
如果 renameTo() 失败,您需要将其复制到新位置,然后删除原始位置。
回答by Jonathan Feinberg
The problem is not that a symlink is involved; the problem is that you can't atomically rename across filesystems. The meta-problem is that the Java File operations are badly designed, and don't throw proper exceptions, and provide no error codes when something fails!
问题不在于涉及符号链接;问题是你不能跨文件系统自动重命名。元问题是 Java 文件操作设计得很糟糕,不会抛出适当的异常,并且在出现故障时不提供错误代码!
回答by Poindexter
How about:
怎么样:
a.renameTo(new File("/your/path/here/");
回答by Trevor Harrison
I think you are confusing things. A java.util.File doesn't represent a file on some filesystem. It represents a path to a file.
我认为你在混淆事情。java.util.File 不代表某些文件系统上的文件。它代表文件的路径。
回答by big lep
Renaming files is also highly problematic accross file systems. See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4073756. Commenters of the bug report posted some sample code and also pointed out that you can use Process.exec. Both Apache Commons IO and and Google Guava have utilities for safely moving files as well:
跨文件系统重命名文件也是一个很大的问题。请参阅http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4073756。错误报告的评论者发布了一些示例代码,并指出您可以使用 Process.exec。Apache Commons IO 和 Google Guava 都有用于安全移动文件的实用程序: