Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 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 */  } 
like image 822
java.is.for.desktop Avatar asked Dec 16 '09 12:12

java.is.for.desktop


People also ask

How do I rename a file programmatically?

File from = new File(directory, "currentFileName"); For safety, Use the File. renameTo() .

Which method is used to rename the file in Java?

In Java we can rename a file using renameTo(newName) method that belongs to the File class. Parameters: dest – The new abstract pathname for the existing abstract pathname.


2 Answers

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.

like image 197
Avner Avatar answered Oct 04 '22 03:10

Avner


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

like image 44
Alan Avatar answered Oct 04 '22 03:10

Alan