如何在 Java 7 中重命名(而不是移动)文件? [英] How do I rename (not move) a file in Java 7?

查看:20
本文介绍了如何在 Java 7 中重命名(而不是移动)文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 JDK7 中所有这些新的 File 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?处理符号链接

问题是:我必须使用名称和位置在运行时已知的文件来执行此操作.所以,我需要的是一种安全方法(没有特殊的副作用)来创建一些旧名称路径的新名称路径.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆