Java file rename of file batch rename instance program code share

  • 2020-04-01 02:31:31
  • OfStack

First, look up the renameTo() method for renaming files in Java.

I put 180 images under d:\\backup and rename them with the following program:


public void reName(){
        String dir = "D:\backup\";
        File file = new File(dir);
        String fileName[] = file.list();
        int number = fileName.length;
        File newFile[] = new File[number];

        System.out.println("number = " + number);
        for(int i=0; i<number; i++) {
            System.out.println((i+1) + ":" + fileName[i]);
            newFile[i] = new File(dir+fileName[i]);
        }
        System.out.println("============ The divider =============");
        for(int i=0; i<number;i++){
            boolean flag = newFile[number - (i+1)].renameTo(new File(dir + (i+1)+".bmp"));
            if(flag){
                System.out.println(" Rename successful "+(i+1));
            } else {
                System.out.println(" failure ");
            }
        }
    }

PS: the failure of Java renaming mainly has the following reasons:

1. Source file not saved or not writable.
2. The target file already exists.
3. When the source file and the target are not in the same disk, are the file formats of different disks the same?

The following is a file name to be modified and the file name to be modified is stored in an array for renaming



    public void reName_1(String from[], String to[]){
        int fileLength = from.length;
        boolean flag = false;
        boolean isOk = false;
        int count = 0;
        if(fileLength != to.length){
            System.out.println(" The length of the array passed in is inconsistent, so the rename operation is not performed ");
            return;
        }else{
            for(int i=0;i<fileLength;i++){
                for(int j=0;j<fileLength;j++){
                    if(from[i].equals(to[j]) ){
                        flag = false;
                        System.out.println("error: The same file name exists, the system rejects the rename operation ");
                        return;
                    }else{
                        flag = true;
                    }
                }
            }
            if(flag){
                System.out.println(" Start work on file renaming ");
                for(int i=0;i<fileLength;i++){
                    isOk = new File(from[i]).renameTo(new File(to[i]));
                    if(isOk){
                        System.out.println(" brother " + (i+1) +" Rename the file successfully ");
                        count++;
                    }
                }
                if(count == fileLength){
                    System.out.println(" All renaming successful ");
                }else{
                    System.out.println(" An unsuccessful file exists for renaming. Please manually review the changes ");
                }
            }
        }
    }


Related articles: