天天看點

一個檔案工具類

最近陸陸續續的在做一些和檔案相關的工作,今天無事就整理了一些近來整理的處理檔案的工具類,有原創也有從網上拿來直接用的,拿來分享,以後繼續完善。

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)));
	}

}
           

繼續閱讀