公司最近有一个从ftp批量下载文件的需求,但是文件名重复总会报错
没办法,自己下班后写了一个小算法
仿照桶排序的原理,实现了这个小功能,直接上代码:
- String[] test = {“hahaha.txt”,“wekje.doc”,“学习.pdf”,“wekje.doc”,“学习.pdf”,
- “hahaha.txt”,“学习.pdf”,“wekje.doc”,“ewheuhiq.jpg”,“学习.pdf”,“Du2Cm_I0Z1x081534·386137_10s.mp4”,“Du2Cm_I0Z1x081534·386137_10s.mp4”};
- String[] strlist = new String[1];
- int [] times = new int[1];
- times[0] = 1;
- System.out.println(“整理前的文件名数组”+Arrays.toString(test));
- for(int i=0;i<test.length;i++){
- int target = 0;
- if(i==0){
- strlist[i] = test[i];
- }else{
- boolean flag = false;
- for(int j=0;j<times.length;j++){
- if(test[i].equals(strlist[j])){
- flag = true;
- target = j;
- break;
- }else{
- continue;
- }
- }
- if(flag){
- String[] spi = test[i].split(“\\.”);
- StringBuilder sb = new StringBuilder(spi[0]);
- sb.append(“(“).append(times[target]+“”).append(“)”)
- .append(“.”).append(spi[1]);
- test[i] = sb.toString();
- times[target] += 1;
- }else{
- strlist = Arrays.copyOf(strlist, strlist.length+1);
- times = Arrays.copyOf(times, times.length+1);
- strlist[strlist.length-1] = test[i];
- times[times.length-1] = 1;
- }
- }
- }
- System.out.println(“处理后的文件名数组”+Arrays.toString(test));