Rename/Move Files Using java.io.File API
1. Rename a File in Place
Rename a file in the original place is trivial by using renameTo() method in java.io.File class. The following code snapshot will change a file name from “oldName.pdf” to “newName.pdf”:
String oldName = “oldName.pdf”;
String newName = “newName.pdf”;
File f = new File(oldName);
f.renameTo(newName);
It is also easy to rename a file, and move the file to an existing directory. The following code will change the file name from “oldName.pdf” to “newName.pdf”, and also move the file from “C:\oldDir” to “C:\newDirsubDir” provide “C:\newDir\subDir” exists:
String oldDir = “C:\\oldDir\\”;
String oldName = “oldName.pdf”;
String newDir = “C:\\oldDir\subDir\\”;
String newName = “newName.pdf”;
File f = new File (oldDir, oldName);
f.renameTo(newDir + newName);
3. Rename/Move a File to an Directory that does not exist
The piece of code above won’t work if C:\newDir\subDir\ does not exist. However, we still can achieve our goal by a little more work. Here is how we do:
String oldDir = “C:\\oldDir\\”;
String oldName = “oldName.pdf”;
String newDir = “C:\\oldDir\\subDir\\”;
File pDir = new File(newDir);
pDir.mkroots();
String newName = “newName.pdf”;
File f = new File (oldDir, oldName);
f.renameTo(newDir + newName);
13 comments:
java.io.File has no rename() method...perhaps you mean renameTo()?
Yes, you are right. There is no such rename() method in java.io.File It should be renameTo().
Thanks for pointing out my mistake.
Ya It's working fine only if the source and destination are on the same drive.
Well, on Windows, I am able to copy files over to/from a shared network drive.
The JavaDocs of renameTo() say that the ability to move a file depends on the capability of the OS. On Windows you can always move a file. On Unix you can only move if the file is on the same file system.
Hey, that was a very useful code. Thanks
I'm actually having a lot of trouble getting this to work. A simple google search reveals that this is a huge problem that bothers many people. A simple thing that doesn't work all the time!
True!
it could use like this
f.renameTo(new File(newFileName));
Unfornatly this doesn't work on Windows if the source and destonation file is in your My Documents directory. For example, try renaming a file, using renameTo, which is located in your My Documents directory. This will fail. This is due to a huge Java bug in Windows that prevents this.
Yes it is true it doesnot work for files in My Documents. If you put the files in C drive it works. Thanks
the last redline trys renameTo() with Strings. But renameTo() needs a File object as parameter!
Thanks
Post a Comment