Skip to content

Instantly share code, notes, and snippets.

@manzke
Created December 28, 2010 15:24
Show Gist options
  • Save manzke/757320 to your computer and use it in GitHub Desktop.
Save manzke/757320 to your computer and use it in GitHub Desktop.
Replace special characters of File and Folder names with new ones.
import java.io.File;
public class Renamer {
private boolean dryRun = true;
private String in = "&";
private String out = "-";
private File root;
private void init(String[] args){
String rootFolder = args[0];
root = new File(rootFolder);
if(!root.exists()){
System.out.println("Root-Folder "+rootFolder+" doesn't exists.");
}
if(args.length == 2){
dryRun = (args[1].equalsIgnoreCase("process") ? true : false);
}
}
public void run(){
File newRoot = rename(root);
iterate(newRoot);
}
private void iterate(File folder){
File[] files = folder.listFiles();
for(File file : files){
if(file.isDirectory()){
File renamed = rename(file);
iterate(renamed);
}else if(file.isFile()){
rename(file);
}
}
}
private File rename(File file){
String name = file.getName();
String newName = name.replace(in, out);
if(name.equals(newName)){
//no replacing needed
return file;
}
File newFile = new File(file.getParent()+File.separator+newName);
if(dryRun){
System.out.println("[DRYRUN] Renaming from "+file.getAbsolutePath()+" to "+newFile.getAbsolutePath());
return file;
}
if(newFile.exists()){
System.out.println(file.getAbsolutePath()+" can't be renamed to "+newFile.getAbsolutePath()+" because new Path already exists.");
return file;
}
boolean renamed = file.renameTo(newFile);
if(!renamed){
System.out.println(file.getAbsolutePath()+" can't be renamed to "+newFile.getAbsolutePath()+". Cause is unknown. Maybe locked?");
return file;
}
return newFile;
}
/**
* @param args
*/
public static void main(String[] args) {
if(args == null || args.length == 0){
System.out.println("Please pass the Root-Folder.");
System.exit(0);
}
Renamer renamer = new Renamer();
renamer.init(args);
renamer.run();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment