[英]moving File leads to file with path separator “/” in filename
I try to move a file from one directory to another. 我尝试将文件从一个目录移动到另一个目录。 I do this with
我这样做
File fileToMove = new File("/Users/kai-dj/separator_problem/from/file_to_move.file");
File destDir = new File("/Users/kai-dj/separator_problem/to");
if (fileToMove.exists() && destDir.isDirectory()) {
fileToMove.renameTo(new File(destDir.getAbsolutePath()+File.pathSeparator+fileToMove.getName()));
}
I'd expect to find file_to_move.file
in folder /Users/kai-dj/separator_problem/to
after execution, but I get a file named to/file_to_move.file
placed in the parent folder /Users/kai-dj/separator_problem
. 我希望执行后在
/Users/kai-dj/separator_problem/to
文件夹中找到file_to_move.file
,但是我将名为 to/file_to_move.file
的文件放在父文件夹/Users/kai-dj/separator_problem
。 At least that's what Finder shows. 至少那是Finder所显示的。
As I thought: "File names mustn't contain path separator characters, this can't be true.", I also checked what ls
would output in terminal: 正如我认为的那样:“文件名不能包含路径分隔符,这不能成立。”,我还检查了
ls
在终端中将输出什么:
mac-book:separator_problem kai-dj$ ls
from to:file_to_move.file
to
OK – seems no /
in file name. OK –似乎没有
/
文件名。 Very strange nontheless. 尽管如此,还是很奇怪。 Why does Finder show it as file name containing
/
? Finder为什么将其显示为包含
/
文件名? Why does Java rename the file to <dirname>:<filename>
– especially even when I used File.pathSeparator
, not /
and certainly not :
? Java为什么将文件重命名为
<dirname>:<filename>
–尤其是即使我使用File.pathSeparator
而不是/
,当然也没有:
?
I also tried with Files.move
– same result. 我也尝试了
Files.move
–同样的结果。
EDIT: Solved, but I'd still love to know, why Finder shows :
as /
^^ 编辑:解决了,但是我还是很想知道,为什么Finder显示
:
as /
^^
As mentioned in the comment above, the correct member to use is called File.separator
. 如上面的注释中所述,要使用的正确成员称为
File.separator
。
Also, you can avoid using File.separator
in general, and use Paths
instead: 另外,您可以避免一般使用
File.separator
,而应使用Paths
:
System.out.println(Paths.get("/Users/kai-dj/separator_problem/to", fileToMove.getName()).toAbsolutePath());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.