我是 Java 初学者,正在尝试使用文件和目录。我想创建一个程序,在该程序中可以自动更改文件名,同时在所有子目录中搜索无效的文件名。我实际上正在尝试将大量文件加载到服务器上,但服务器设置不允许文件名包含特殊字符。首先,我能够编写代码,如果我将路径传递到目录,它会重命名该目录中具有无效名称的所有文件:
公共(public)类重命名{
public static String baseLoc = "C:/Users/Developer/Desktop/.../Data Cleanup";
public static void main(String[] args) {
//LinkedList<File> fileList = new LinkedList<File>();
File obj = new File(baseLoc);
int count = 0;
for (File file: obj.listFiles())
{
String origName = file.getName();
if (origName.contains("&") || origName.contains("#") || origName.contains("@"))
{
System.out.println("Original name: "+origName);
origName = origName.replaceAll("&", "_and_");
origName = origName.replaceAll("@", "_at_");
String newName = origName.replaceAll("#", "_");
System.out.println("New Name: "+newName);
String newLoc = baseLoc+"/"+newName;
File newFile = new File(newLoc);
System.out.println(file.renameTo(newFile));
count++;
}
}
}
}
现在我想做同样的事情,但只是这一次我希望所有文件都被重命名,即使是在子目录中。有人可以指导我如何实现这一目标吗?
最佳答案
递归是你的 friend
/**Removes 'invalid' characters (&,#,@) from pathnames in the given folder, and subfolders, and returns the number of files renamed*/
public int renameDirectory(File base){
//LinkedList<File> fileList = new LinkedList<File>();
int count=0;//count the renamed files in this directory + its sub. You wanted to do this?
//Process each file in this folder.
for (File file: base.listFiles()){
String origName = file.getName();
File resultFile=file;
if (origName.contains("&") || origName.contains("#") || origName.contains("@")){
//I would replace the if statement with origName.matches(".*[&#@].*") or similar, shorter but more error prone.
System.out.println("Original name: "+origName);
origName = origName.replaceAll("&", "_and_");
origName = origName.replaceAll("@", "_at_");
String newName = origName.replaceAll("#", "_");
System.out.println("New Name: "+newName);
String newLoc = baseLoc+File.separator+newName;//having "/" hardcoded is not cross-platform.
File newFile = new File(newLoc);
System.out.println(file.renameTo(newFile));
count++;
resultFile=newFile;//not sure if you could do file=newFile, tired
}
//if this 'file' in the base folder is a directory, process the directory
if(resultFile.isDirectory()){//or similar function
count+=renameDirectory(resultFile);
}
}
return count;
}
关于java - 更改父目录和子目录中的文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19686475/