Renaming a File or Directory

// File (or directory) with old name File file = new File("oldname"); // File (or directory) with new name File file2 = new File("newname"); // Rename file (or directory) boolean success = file.renameTo(file2); if (!success) { // File was not successfully renamed }

Comments

14 Jan 2010 - 2:42am by Anthony (not verified)

Recursive Renaming of Files :-

import java.io.File;
import java.util.StringTokenizer;

/*Change the extension name of the file recursively
for multiple directories
*/
public class renFile {
static String reName ="";
static StringTokenizer str =null;
static File files[] =null;
static final String ext = ".doc";//Extension to Change to
public void Innundo(String path){
String t;
try {
File file = new File(path);
files = file.listFiles();
for(File fl : files){
if(fl.isDirectory()){
System.out.println("Directory name:"+fl.toString());
Innundo(fl.toString());

}else {
System.out.println("File name:"+fl.toString());
if(fl.isFile()){
t = fl.getName();
str = new StringTokenizer(t,".");
if(str.hasMoreTokens()){
t= str.nextToken();
t= fl.getParent()+"\\"+t+ext;
System.out.println("Changed Name "+t);
fl.renameTo(new File(t));
}
}
else {System.out.println(fl.getName()+" Not A File! ");}
}
}
}catch(Exception e){
e.printStackTrace();

}
}
public static void main(String[] args) {
String path="C:/Path_To_Directory";
renFile re = new renFile();
re.Innundo(path);
}
}
//http://blog.mysuccessmantra.com

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.