如何在JDK7中重命名(不移动)文件? [英] How do I rename (not move) a file in JDK7?
问题描述
比方说,我有一个 Path
并且想要重命名该文件,它表示。
如果预期再次出现 Path
,我该如何指定新名称?
路径p = / *路径/ home / me / file123 * /;
路径名称= p.getName(); / *给我file123 * /
name.moveTo(/ *什么现在?* /); / *如何将file123重命名为file456? * /
注意:为什么我需要 JDK7 ?处理符号链接!
问题是:我必须使用文件来处理运行时已知的名称和位置。所以,我需要的是一个安全的方法(没有特殊的副作用)来创建一个新的名称 - 路径的一些旧名称路径
Path newName(Path oldName,String newNameString){
/ * magic * /
}
您有一个路径字符串,您需要创建一个Path实例。你可以用getPath方法或解决方法来做到这一点。这里有一个方法:
路径dir = oldFile.getParent();
路径fn = oldFile.getFileSystem()。getPath(newNameString);
路径目标=(dir == null)? fn:dir.resolve(fn);
oldFile.moveTo(target);
请注意,它会检查父项是否为空(看起来像您的解决方案不这样做) / p>
I'm a bit confused with all these new File I/O classes in JDK7.
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? */
NOTE: Why do I need JDK7? Handling of symbolic links!
Problem is: I have to do it with files, which 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 */
}
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);
Note that it checks if parent is null (looks like your solution don't do that).
这篇关于如何在JDK7中重命名(不移动)文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!