博客主机
A-A+

图片文件批量重命名工具

2009年10月06日 杂七杂八 暂无评论 阅读 183 次
摘要:

每次浏览网页,看见不错的创意,或是漂亮的图片或风景,总是“右键”—-“另存为”。为了留住过去美好的瞬间,总喜欢留下以前的照片,朋友的、亲人的、自己的……随着时间慢慢推移,呵呵,现在的照片居然多达几百兆!想整理但又太烦锁了,嘿嘿,索性写个程序来整理一哈!

博客主机

       每次浏览网页,看见不错的创意,或是漂亮的图片或风景,总是“右键”----“另存为”。为了留住过去美好的瞬间,总喜欢留下以前的照片,朋友的、亲人的、自己的……随着时间慢慢推移,呵呵,现在的照片居然多达几百兆!想整理但又太烦锁了,嘿嘿,索性写个程序来整理一哈!
代码如下:

import java.io.*;
/**
 * <p>Title: FileConsolidation</p>
 * <p>Description: 图片文件批量重命名工具</p>
 * <p>Copyrigh:  Copyright (c) 2009</p>
 * @author Huang Zhiqiang
 * @version 1.0beta
 */
public class FileConsolidation {
	
	//需要整理的文件夹路径
	static String path = "C:\Documents and Settings\Administrator\桌面\down";
	
	//重命名文件时使用的前缀,如"xx-",重命名后文件名会改为如"xx-001.jpg"
	static String prefix = "IMG-";
	
	//图片文件重命名初始化参数
	static int i = 0;
	
	//用于匹配的图片文件类型
	static String ImageFileType = ".BMP|.JPG|.JPEG|.JPE|.JFIF|.GIF|.TIF|.TIFF|.PNG|.ICO";
	
	//整理或重命名后的新文件名
	static String newfileName = null;
	
	public static void Dir(String path1) {
		try {
			File file = new File(path1);// 上层目录
			String list[] = file.list();
			// 遍历循环所有文件名称
			for (String string : list) {
				File nextfile = new File(file.getPath() + "\" + string);// 下一层目录
				if (nextfile.isDirectory()) { //是否为文件夹
					Dir(nextfile.getPath());
				} else {
					if(isImge(nextfile)) { 
						i++;
						newfileName = prefix + newfileName(i) + getFileType(nextfile);
					} else {
						newfileName = nextfile.getName();
					}
					nextfile.renameTo(new File( path + "\" + newfileName));//重命名或整理文件
					System.out.println( nextfile.getName() + " ----> " + newfileName);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	//给图片重新命名
	public static String newfileName(int i) {
		if(i <= 9){
			return "000"+i;
		}else if(10 <= i && i <= 99){
			return "00"+i;
		}else if(100 <= i && i <= 999){
			return "0"+i;
		}else{
			return String.valueOf(i);
		}
	}
	
	//判断是否为图片文件
	public static Boolean isImge(File _file) {
		return getFileType(_file).toUpperCase().matches(ImageFileType);
	}
	
	//获得文件的后缀名
	public static String getFileType(File _file) {	
		return _file.getName().substring(_file.getName().indexOf("."));
	}
	
	public static void main(String[] args) {
		Dir(path);
		System.out.println("整理完毕~!");
		
	}
}
博客主机

给我留言