JAVA 遍历文件夹下文件并更改文件名称

  周末因为一些原因,需要批量更改一些文件的名称,使其随机,就随手写了点代码。

增加一个随机字母:

public static void changeName(String path){
		File file = new File(path);
		File[] files = file.listFiles();
		for (int i = 0; i < files.length; i++) {
			if(files[i].isDirectory()){
				changeName(files[i].toString());
			}else{
				String name = files[i].getAbsolutePath();
				files[i].renameTo(new File("G:\\newSong\\"+getChar()+files[i].getName()));
			}
			
		}
		
	}
	
	public static String getChar(){
		String[] datas = {"a","b","c","d","e","f","g","h","k","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
		Random r = new Random();
		return datas[r.nextInt(datas.length-1)];
	}
	public static void main(String[] args) {
		changeName("G:\\song");
	}

  删除掉随机字母

public static void changeName(String path){
		File file = new File(path);
		File[] files = file.listFiles();
		for (int i = 0; i < files.length; i++) {
			if(files[i].isDirectory()){
				changeName(files[i].toString());
			}else{
				String name = files[i].getAbsolutePath();//newSong\\
				String nameStr = files[i].getName().substring(1,files[i].getName().length());
				files[i].renameTo(new File("G:\\song\\"+nameStr));
			}
			
		}
		
	}
	
	public static String getChar(){
		String[] datas = {"a","b","c","d","e","f","g","h","k","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
		Random r = new Random();
		return datas[r.nextInt(datas.length-1)];
	}
	public static void main(String[] args) {
		changeName("G:\\newSong");
	}

  

转载于:https://www.cnblogs.com/yeyuchangfeng/p/4657304.html

你可能感兴趣的:(java)