The IO processing in Java implements file batch renaming operations, and implements file external operations through the File class

  • Java's renaming operation needs to be implemented through the rename function, including
  • File newFile=new File(file.getParent(),filename);//First generate a new file and file name, file renaming needs to obtain the parent directory
    file.renameTo(newFile);//Realize file renaming operation
import java.io.File;

public class FileRename {
    
    
    public static void main(String[] args) {
    
    
        long start=System.currentTimeMillis();
        File file=new File("F:"+File.separator+"snake");//需要操作的文件目录
        renameFile(file);
        long end =System.currentTimeMillis();
        System.out.println("花费时间:"+(end-start));
    }
    public static void renameFile(File file){
    
    
        if(file.isDirectory()){
    
    
            File results[]=file.listFiles();
            if(results!=null){
    
    
                for(int i=0;i<results.length;i++){
    
    
                    renameFile(results[i]);//递归查看子目录的内容,直到找到文件为止。
            }
            }

        }if(file.isFile()){
    
    //遍历所有目录中的文件夹,只要是文件,就要实现重命名操作
            String filename=null;
            if(file.getName().contains(".")){
    
    //文件中名称是否包含.
            filename=file.getName().substring(0,file.getName().lastIndexOf("."))+".txt";//实现截取从第一个字母到最后一个点的操作,再添加上txt字符串
            }else{
    
    
                filename=file.getName()+".txt";//对于不含有.的文件名,直接添加.txt后缀。
            }
            File newFile=new File(file.getParent(),filename);
            file.renameTo(newFile);//文件的重命名操作.


        }
    }
}

Guess you like

Origin blog.csdn.net/lyl140935/article/details/108560362