How do I rename (not move) a file in JDK7?

2019-01-17 20:40发布

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 */ 
}

6条回答
不美不萌又怎样
2楼-- · 2019-01-17 21:20

If the destination path is identical to the source path except for the name of the file, it will be renamed rather than moved.

So for your example, the moveto path should be

/home/me/file456
查看更多
放我归山
3楼-- · 2019-01-17 21:21

If you take a look at Apache Commons IO there's a class called FileNameUtils. This does a ton of stuff wrt. file path names and will (amongst other things) reliably split up path names etc. I think that should get you a long way towards what you want.

查看更多
相关推荐>>
4楼-- · 2019-01-17 21:21

If you can't get Java to do what you want with Unix I recommend Python scripts (run by your Java program). Python has get support for Unix scripting and it's not Perl :) This might sound inelegant to you but really in a larger program you'll benefit from using the right tool for the job.

查看更多
Ridiculous、
5楼-- · 2019-01-17 21:26

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).

查看更多
forever°为你锁心
6楼-- · 2019-01-17 21:41

In JDK7, Files.move() provides a short and concise syntax for renaming files:

Path newName(Path oldName, String newNameString) {
    return Files.move(oldName, oldName.resolveSibling(newNameString));
}

First we're getting the Path to the new file name using Path.resolveSibling() and the we use Files.move() to do the actual renaming.

查看更多
爱情/是我丢掉的垃圾
7楼-- · 2019-01-17 21:46

OK, after trying everything out, it seems I found the right method:

// my helper method
Path newName(Path oldFile, String newNameString){
    // the magic is done by Path.resolve(...)
    return oldFile.getParent().resolve(newNameString);
}

// so, renaming is done by:
oldPath.moveTo(newName(oldFile, "newName"));
查看更多
登录 后发表回答