java修改当前目录和目录以下所有文件夹中的jpg图片、mp3音频文件的后缀名
import java.io.File;
import java.util.Scanner;
public class test2pro {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("please choose whether to modify or recover?");
String choose = sc.nextLine();
int flag = 0;
if(choose.equals("modify")){
flag =1;
}else{
flag = 0;
}
modifyExtension(System.getProperty("user.dir"),flag);
System.out.println("done");
}
//when flag = 1, change the extension ;
//when flag =0 , just recover it;
public static void modifyExtension(String path,int num) {
File f = new File(path);
File[] fs = f.listFiles();
for (File subFile : fs) {
if (subFile.isDirectory()){
modifyExtension(subFile.getPath(),num);
} else {
String name = subFile.getName();
int len = name.length()-3;
if(num>0){
if (name.endsWith("jpg")) {
modifyExtension(subFile,"ide",len,name);
}
if (name.endsWith("mp3")) {
modifyExtension(subFile,"vid",len,name);
}
}else{
if (name.endsWith("ide")) {
modifyExtension(subFile,"jpg",len,name);
}
if (name.endsWith("vid")) {
modifyExtension(subFile,"mp3",len,name);
}
}
}
}
}
public static void modifyExtension(File f,String finalExtensionName,int len,String name){
f.renameTo(new File(f.getParent() + "/" + name.substring(0, len) + finalExtensionName));
}
}