今天收到一个任务,将所有图片进行重命名,于是就有了下面的函数,循环遍历文件夹进行文件重命名.
1 private static void uploadImageFile(File file) { 2 File[] imageList = file.listFiles(); 3 // 循环遍历文件 4 for (File picFile : imageList) { 5 if (picFile.isFile()) { 6 String fileName = picFile.getName(); 7 String suffix = fileName.substring(fileName.lastIndexOf(".")); 8 String order = new StringBuilder().append(prefix + ((int)(Math.random() * 9000 + 1000))).append(suffix) 9 .toString();10 File renameFile = new File(file + "\\" + order);11 picFile.renameTo(renameFile);12 System.out.println(picFile.getName());13 }else if(picFile.isDirectory()){14 uploadImageFile(picFile);15 }16 17 }18 }
按照随机身份证格式,对图片进行重命名完整类
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
1 public class RenamePic { 2 3 /** 4 * 测试主方法 5 * @author fgq 2017年7月13日 下午4:48:56 6 * @param args 7 */ 8 public static void main(String[] args) { 9 String path = "F:\\fgq_test";10 File file = new File(path);11 long startTime = System.currentTimeMillis();12 cycleDealFile(file);13 System.out.println(System.currentTimeMillis() - startTime);14 15 }16 17 /**18 * 循环处理文件19 * @author fgq 2017年7月13日 下午4:48:3520 * @param file21 */22 private static void cycleDealFile(File file) {23 File[] imageList = file.listFiles(); 24 // 循环遍历文件25 for (File fileItem : imageList) {26 if (fileItem.isFile()) {27 renameFile(fileItem);28 }else if(fileItem.isDirectory()){29 cycleDealFile(fileItem);30 }31 }32 }33 34 /**35 * 文件重命名36 * @author fgq 2017年7月13日 下午4:47:4237 * @param file38 */39 private static void renameFile(File file){40 String fileName = file.getName();41 String suffix = fileName.substring(fileName.lastIndexOf("."));42 String order = new StringBuilder().append(generalId()).append(suffix)43 .toString();44 File renameFile = new File(file.getParentFile() + "\\" + order);45 file.renameTo(renameFile);46 }47 48 /**49 * 生成伪身份证50 * @author fgq 2017年7月13日 下午4:47:1451 * @return52 */53 private static String generalId() {54 55 int areaCode = getRandNum(100000, 999999);56 int yearNum = getRandNum(1600, 2017);57 58 int monthNum = getRandNum(1, 12);59 String monthStr = String.valueOf(monthNum);60 if (Integer.parseInt(monthStr) < 10) {61 monthStr = "0" + monthNum;62 }63 64 int dayNum = getRandNum(1, 30);65 String dayStr = String.valueOf(dayNum);66 if (Integer.parseInt(dayStr) < 10) {67 dayStr = "0" + dayNum;68 }69 int suffix = getRandNum(1000, 9999);70 71 return new StringBuilder().append(areaCode).append(yearNum).append(monthStr).append(dayStr).append(suffix).toString();72 }73 74 /**75 * 获取范围内的随机数76 * @author fgq 2017年7月13日 下午4:46:5577 * @param min78 * @param max79 * @return80 */81 private static int getRandNum(int min, int max) {82 int randNum = min + (int)(Math.random() * ((max - min) + 1));83 return randNum;84 } 85 }