当前位置:网站首页>[technical fragment] implementation of renaming and filtering duplicate name files with suffixes

[technical fragment] implementation of renaming and filtering duplicate name files with suffixes

2022-06-10 20:29:00 Castanea henryi

 Insert picture description here

Preface

Rename and filter files with duplicate names and suffixes

If there is a duplicate name , It's in the back ( Before extension ) suffix “_1”, “_2”, “_3”, … Until the file name does not repeat .

Realization

public class Main {

    public static void main(String[] args) {
        String originalFileName = "1232121421412(0).jpg";

        Boolean repeat = true;
        //  Whether the file has a duplicate name 
        StringBuilder fileName = new StringBuilder();

        //  If there is a duplicate name , Then add _1 suffix 
        if (repeat) {
            int suffixNumber = 0;
            String fileExtensionName = "";

            //  Separate file extensions (.jpg .png ... )
            for (int i = originalFileName.length() - 1; i > 0; i--) {
                if (originalFileName.charAt(i) == '.') {
                    fileExtensionName = originalFileName.substring(i, originalFileName.length());
                    fileName = new StringBuilder(originalFileName.substring(0, i));
                    break;
                }
            }

            //  Add _1 suffix 
            fileName.append("_" + ++suffixNumber);
            //  If it already exists  _1  suffix , Is changed to  _2 , _3 ,... Until not repeated 
            while (repeat) {
                //  Add our "_" All subsequent numeric characters are deleted 
                for (int length = fileName.length(); length > 0; length--) {
                    char c = fileName.charAt(length - 1);
                    if (c != '_') {
                        fileName.delete(length - 1, length);
                    }
                    else {
                        break;
                    }
                }
                fileName.append(++suffixNumber);

                //  hypothesis _23 Do not repeat when 
                if ("23".equals(fileName.substring(fileName.length() - 2, fileName.length()))) {
                    break;
                }
            }
            //  Merge extensions and return 
            fileName.append(fileExtensionName);
            System.out.println(fileName);
        }

    }

}

    

function

 Insert picture description here

原网站

版权声明
本文为[Castanea henryi]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/161/202206101921176086.html