如何在Java 7中重命名(不移动)文件? [英] How do I rename (not move) a file in Java 7?
问题描述
我对JDK7中所有这些新的文件I/O类感到困惑.
I'm a bit confused with all these new File I/O classes in JDK7.
比方说,我有一个Path
,想重命名它代表的文件.再次需要输入Path
时,如何指定新名称?
Let's say, I have a Path
and want to rename the file it represents. How do I specify the new name, when again a Path
is expected?
Path p = /* path to /home/me/file123 */;
Path name = p.getName(); /* gives me file123 */
name.moveTo(/* what now? */); /* how to rename file123 to file456? */
注意:为什么我需要 JDK7 ? 符号链接的处理!
NOTE: Why do I need JDK7? Handling of symbolic links!
问题是:我必须对名称和位置在运行时已知的文件进行处理.因此,我需要的是一种安全方法(没有特殊的副作用),以创建一些旧名称路径的新名称路径.
Problem is: I have to do it with files whose names and locations are known at runtime. So, what I need, is a safe method (without exceptional side-effects) to create a new name-Path of some old name-Path.
Path newName(Path oldName, String newNameString){
/* magic */
}
推荐答案
您有一个路径字符串,需要创建一个Path实例.您可以使用getPath方法执行此操作或解决.这是一种方法:
You have a path string and you need to create a Path instance. You can do this with the getPath method or resolve. Here's one way:
Path dir = oldFile.getParent();
Path fn = oldFile.getFileSystem().getPath(newNameString);
Path target = (dir == null) ? fn : dir.resolve(fn);
oldFile.moveTo(target);
请注意,它会检查parent是否为null(看来您的解决方案不这样做).
Note that it checks if parent is null (looks like your solution don't do that).
这篇关于如何在Java 7中重命名(不移动)文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!