一个文件工具类

最近陆陆续续的在做一些和文件相关的工作,今天无事就整理了一些近来整理的处理文件的工具类,有原创也有从网上拿来直接用的,拿来分享,以后继续完善。

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.apache.tools.zip.ZipOutputStream;

/**
 * 操作文件工具类
 * 
 * @author Administrator 2011-8-5 下午03:40:00
 * 
 * 
 */
public class FileUtil {

	static final int BUFFER = 1024;

	/**
	 * 获取单个文件的MD5值
	 * 
	 * @param file
	 * @return
	 */
	public static String getFileMD5(File file) {
		if (!file.isFile()) {
			return null;
		}
		MessageDigest digest = null;
		FileInputStream in = null;
		byte buffer[] = new byte[1024];
		int len;
		try {
			digest = MessageDigest.getInstance("MD5");
			in = new FileInputStream(file);
			while ((len = in.read(buffer, 0, 1024)) != -1) {
				digest.update(buffer, 0, len);
			}
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		BigInteger bigInt = new BigInteger(1, digest.digest());
		return bigInt.toString(16);
	}

	/**
	 * 获取文件夹中文件的MD5值
	 * 
	 * @param file
	 * @param listChild
	 *            ;true递归子目录中的文件
	 * @return
	 */
	public static Map<String, String> getDirMD5(File file, boolean listChild) {
		if (!file.isDirectory()) {
			return null;
		}
		// <filepath,md5>
		Map<String, String> map = new HashMap<String, String>();
		String md5;
		File files[] = file.listFiles();
		for (int i = 0; i < files.length; i++) {
			File f = files[i];
			if (f.isDirectory() && listChild) {
				map.putAll(getDirMD5(f, listChild));
			} else {
				md5 = getFileMD5(f);
				if (md5 != null) {
					map.put(f.getPath(), md5);
				}
			}
		}
		return map;
	}

	/**
	 * 给指定的文件重命名,加上指定的字符串
	 * @param file	指定的文件
	 * @param str	加上的字符串
	 * @return	返回文件重名名后的文件名
	 */
	public static String reNameAddStr(File file, String str) {
		String fileName = file.getName();
		
		// 获得去掉后缀名后的文件名
		String name = fileName.substring(0, fileName.lastIndexOf("."));
		
		// 获得文件的后缀名
		String extendName = fileName.substring(fileName.lastIndexOf("."),
				fileName.length());
		
		String destName = name + str + extendName;

		file.renameTo(new File(file.getParent() + "\\" + destName));
		return destName;
	}
	
	/**
	 * 从指定文件的文件名中去掉指定字符串
	 * @param file	指定文件	
	 * @param str	去掉的字符串
	 * @return	返回文件的重命名后的文件名
	 */
	public static String reNameDelStr(File file, String str) {
		
		String fileName = file.getName();
		
		if(fileName == null || str == null || fileName.length() <= str.length()) {
			return "";
		}
		
		// 获得去掉后缀名后的文件名
		String name = fileName.substring(0, fileName.lastIndexOf("."));
		
		//获得去掉str后的文件名
		String realName = name.substring(0,name.length()-str.length());
		
		// 获得文件的后缀名
		String extendName = fileName.substring(fileName.lastIndexOf("."),
				fileName.length());
		
		String destName = realName + extendName;

		file.renameTo(new File(file.getParent() + "\\" + destName));
		return destName;
	}
	
	/**
	 * 把文件重命名,文件名后加上1970年距今的毫秒数,防止文件重名
	 * 
	 * @param fileName
	 * @return
	 */
	public static String reNameAddTime(String fileName) {

		// 获得去掉后缀名后的文件名
		String name = fileName.substring(0, fileName.lastIndexOf("."));

		// 获得文件的后缀名
		String extendName = fileName.substring(fileName.lastIndexOf("."),
				fileName.length());
		return name + new Date().getTime() + extendName;
	}

	/**
	 * 把文件重命名,文件名为1970年距今的毫秒数,防止文件重名
	 * 
	 * @param fileName
	 * @return
	 */
	public static String reNameToTime(String fileName) {

		// 获得文件的后缀名
		String extendName = fileName.substring(fileName.lastIndexOf("."),
				fileName.length());
		return new Date().getTime() + extendName;
	}

	/**
	 * 把文件名进行还原,去掉后面的时间,时间百年内仍是13位
	 * 
	 * @param fileName
	 * @return
	 */
	public static String reNameDelTime(String fileName) {

		// 获得去掉后缀名后的文件名
		String name = fileName.substring(0, fileName.lastIndexOf("."));

		// 获得文件的后缀名
		String extendName = fileName.substring(fileName.lastIndexOf("."),
				fileName.length());

		return name.substring(0, name.length() - 13) + extendName;
	}

	/**
	 * 用zip格式压缩文件
	 * 
	 * @param zipFile
	 *            压缩后的文件名 包含路径 如:"c:\\test.zip"
	 * @param inputFile
	 *            要压缩的文件 可以是文件或文件夹 如:"c:\\test" 或 "c:\\test.doc"
	 * @throws Exception
	 * 
	 *             ant下的zip工具默认压缩编码为UTF-8编码,而winRAR软件压缩是用的windows默认的GBK或者GB2312编码
	 * 
	 *             用ant压缩后放到windows上面会出现中文文件名乱码,用winRAR压缩的文件,用ant解压也会出现乱码,
	 * 
	 *             所以,在用ant处理winRAR压缩的文件时,要设置压缩编码
	 */
	public static void zip(File zipFile, String inputFile) throws Exception {
		File f = new File(inputFile);
		// File temp = new File(zipFileName);
		ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile));

		// 设置压缩编码
		out.setEncoding("GBK");// 设置为GBK后在windows下就不会乱码了,如果要放到Linux或者Unix下就不要设置了
		zip(out, f, "");// 递归压缩方法
		System.out.println("zip done");
		out.close();
	}

	private static void zip(ZipOutputStream out, File f, String base)
			throws Exception {
		System.out.println("Zipping   " + f.getName()); // 记录日志,开始压缩
		if (f.isDirectory()) { // 如果是文件夹,则获取下面的所有文件
			File[] fl = f.listFiles();
			out.putNextEntry(new ZipEntry(base + "/"));// 此处要将文件写到文件夹中只用在文件名前加"/"再加文件夹名
			base = base.length() == 0 ? "" : base + "/";
			for (int i = 0; i < fl.length; i++) {
				zip(out, fl[i], base + fl[i].getName());
			}
		} else { // 如果是文件,则压缩
			out.putNextEntry(new ZipEntry(base)); // 生成下一个压缩节点
			FileInputStream in = new FileInputStream(f); // 读取文件内容
			int len;
			byte[] buf = new byte[BUFFER];
			while ((len = in.read(buf, 0, BUFFER)) != -1) {
				out.write(buf, 0, len); // 写入到压缩包
			}
			in.close();
		}
	}

	/**
	 * 解压缩zip文件
	 * 
	 * @param fileName
	 *            要解压的文件名 包含路径 如:"c:\\test.zip"
	 * @param filePath
	 *            解压后存放文件的路径 如:"c:\\temp"
	 * @throws Exception
	 */
	public static void unZip(String fileName, String filePath) throws Exception {
		ZipFile zipFile = new ZipFile(fileName, "GBK"); // 以“GBK”编码创建zip文件,用来处理winRAR压缩的文件。
		Enumeration emu = zipFile.getEntries();

		while (emu.hasMoreElements()) {
			ZipEntry entry = (ZipEntry) emu.nextElement();
			if (entry.isDirectory()) {
				new File(filePath + entry.getName()).mkdirs();
				continue;
			}
			BufferedInputStream bis = new BufferedInputStream(zipFile
					.getInputStream(entry));

			File file = new File(filePath + entry.getName());
			File parent = file.getParentFile();
			if (parent != null && (!parent.exists())) {
				parent.mkdirs();
			}
			FileOutputStream fos = new FileOutputStream(file);
			BufferedOutputStream bos = new BufferedOutputStream(fos, BUFFER);

			byte[] buf = new byte[BUFFER];
			int len = 0;
			while ((len = bis.read(buf, 0, BUFFER)) != -1) {
				fos.write(buf, 0, len);
			}
			bos.flush();
			bos.close();
			bis.close();
			System.out.println("解压文件:" + file.getName());
		}
		zipFile.close();
	}

	public static void main(String[] args) throws Exception {
		//unZip("D:\\test\\新建文件夹.zip", "D:\\test\\");
		// zip(new File("D:\\test\\新建文件夹.zip"), "D:\\test\\新建文件夹");
		System.out.println(getFileMD5(new File("D:\\test\\新建文件夹.zip")));
		System.out.println(getFileMD5(new File("D:\\test\\1.zip")));
		File file = new File("D:\\test\\test2cf4bb1ab1c4c64c4a504306f9b08556.zip");
		System.out.println(reNameDelStr(file, getFileMD5(file)));
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值