首页 > 代码库 > java打开文件夹(含判断操作系统工具类和解压缩工具类)

java打开文件夹(含判断操作系统工具类和解压缩工具类)

1、Runtime.getRuntime().exec("explorer D:\\Java");


2、java.awt.Desktop.getDesktop().open(new File("D:\\Java"));    

4、java.awt.Desktop.getDesktop().browse(...)


3、    try {  
                String[] cmd = new String[5];  
                cmd[0] = "cmd";  
                cmd[1] = "/c";  
                cmd[2] = "start";  
                cmd[3] = " ";  
                cmd[4] = FILE_PATH;  
                Runtime.getRuntime().exec(cmd);  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  

4、    /*** 
         *  
         * @param folder 
         *            : directory 
         */  
        public static void open_directory(String folder) {  
            File file = new File(folder);  
            if (!file.exists()) {  
                return;  
            }  
            Runtime runtime = null;  
            try {  
                runtime = Runtime.getRuntime();  
                if (!SystemUtil.isWindows) {  
                    // System.out.println("is linux");  
                    runtime.exec("nautilus " + folder);  
                } else {  
                    runtime.exec("cmd /c start explorer " + folder);  
                }  
            } catch (IOException ex) {  
                ex.printStackTrace();  
            } finally {  
                if (null != runtime) {  
                    runtime.runFinalization();  
                }  
            }  
        }  

5、    /*** 
         *  
         * @param filePath 
         *            : only regular file 
         */  
        public static void open_file(String filePath) {  
            File file = new File(filePath);  
            if (!file.exists()) {  
                return;  
            }  
            Runtime runtime = null;  
            try {  
                runtime = Runtime.getRuntime();  
                if (!SystemUtil.isWindows) {  
                    // System.out.println("is linux");  
                    runtime.exec("nautilus " + filePath);  
                } else {  
                    runtime.exec("cmd /c start explorer /select,/e, " + filePath);  
                }  
            } catch (IOException ex) {  
                ex.printStackTrace();  
            } finally {  
                if (null != runtime) {  
                    runtime.runFinalization();  
                }  
            }  
        }  



其他工具类

package com.common.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.crypto.Cipher;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import org.apache.commons.lang.StringUtils;

import com.io.hw.exception.MyException;
import com.io.hw.file.util.FileUtils;
import com.string.widget.util.ValueWidget;
import com.time.util.TimeHWUtil;

public class SystemUtil {
	public static final String OSNAME = System.getProperty("os.name");
	public static final String OSARCH = System.getProperty("os.arch");
	public static final String SEPARATOR = System.getProperty("file.separator");
	public static final String USER_DIR = System.getProperty("user.dir");
	public static final String CURR_ENCODING = System
			.getProperty("file.encoding");
	public static final String LINE_SEPARATOR = System
			.getProperty("line.separator");
	public static final String CRLF = LINE_SEPARATOR; // Carriage Return/Line
	// Feed
	public static final String CRLF_LINUX = "\n";
	public static final String CHARSET_UTF = "UTF-8";
	public static final String CHARSET_GBK = "GBK";
	public static final String CHARSET_GB2312 = "GB2312";
	public static final String CHARSET_GB18030 = "GB18030";
	public static final String CHARSET_UNICODE = "UNICODE";
	public static final String CHARSET_ISO88591 = "ISO-8859-1";

	public static boolean isWindows = false;
	public static boolean isHP_UX = false;
	public static boolean isSolaris = false;
	public static boolean isOS32bit = true;
	public static final int BUFF_SIZE = 4096;
	public static final String KEY_ALGORITHM_RSA = "RSA";
	public final static String KEY_ALGORITHM_DES = "DES";
	public static final String KEY_ALGORITHM_SHA1withRSA = "SHA1withRSA";
	public static final String SIGNATURE_ALGORITHM = "MD5withRSA";
	public static final String KEY_SHA = "SHA";
	public static final String KEY_SHA1 = "SHA-1";
	public static final String KEY_MD5 = "MD5";
	public static final String KEY_HMAC_SHA256 = "HMACSHA256";
	public static final String KEY_HMAC_SHA1 = "HmacSHA1";
	public static final String CERTIFICATEFACTORY_X509 = "X.509";
	public static final char[] HEXCHAR = { '0', '1', '2', '3', '4', '5', '6',
			'7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
	public static BigInteger bigInt1 = BigInteger.valueOf(1l);
	public static final String CONTENTTYPE_HTML = "text/html";
	public static final String CONTENTTYPE_JSON = "application/json";
	public static final String CONTENTTYPE_X_WWW_FORM_URLENCODED = "application/x-www-form-urlencoded";

	public static final String CONTENTTYPE_OCTET_STREAM = "application/octet-stream";

	public static final String PROCOTOL_HTTP = "http";
	public static final String PROCOTOL_HTTPS = "https";
	public static final String COLON = ":";
    /**
     * 字符串空格
     */
    public static final String BLANK = " ";
    public static final String ENGLISH_PERIOD = ".";
	public static final String DIVIDING_LINE = "---------------------------------------";

	public static final int NEGATIVE_ONE = -1;
	public static final String EMPTY = "";
	static {
		if (SystemUtil.OSNAME.toLowerCase().contains("window")) {
			isWindows = true;
		}
		if (SystemUtil.OSNAME.toLowerCase().contains("hp-ux")) {
			isHP_UX = true;
		}
		if (SystemUtil.OSNAME.toLowerCase().contains("Solaris")) {
			isSolaris = true;
		}
		if (SystemUtil.OSARCH.contains("64")) {
			isOS32bit = false;
		}
	}

	private SystemUtil() {
		throw new Error("Don't let anyone instantiate this class.");
	}

	public static void copyFile(String resourceFileName, String targetFileName)
			throws IOException {
		File resourceFile = new File(resourceFileName);
		File targetFile = new File(targetFileName);
		if (!resourceFile.exists()) {
			System.out.println("[copyFile ]: resource file has not been found:"
					+ resourceFileName);
		}
		if (!resourceFile.isFile()) {
			System.out.println("[copyFile ]: directory can not be copyed:"
					+ resourceFileName);
		}

		if (targetFile.isDirectory()) {
			targetFile = new File(targetFile, resourceFile.getName());
		}

		FileInputStream resource = null;
		FileOutputStream target = null;
		try {
			resource = new FileInputStream(resourceFile);
			target = new FileOutputStream(targetFile);
			copyFile(resourceFile, targetFile);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (resource != null) {
				resource.close();
			}
			if (target != null) {
				target.close();
			}
		}
	}

	/**
	 * 
	 * @param srcFile
	 *            :must be regular file,can not be folder;
	 * @param targetFile
	 *            :must be regular file,can not be folder;
	 * @throws IOException
	 */
	public static void copyFile(File srcFile, File targetFile)
			throws IOException {
		FileInputStream in = new FileInputStream(srcFile);

		FileOutputStream out = new FileOutputStream(targetFile);
		copyFile(in, out);

	}

	public static void copyFile(InputStream in, FileOutputStream target)
			throws IOException {
		// File targetFile = new File(targetFileName);
		// FileOutputStream target = null;
		// if (targetFile.isDirectory())
		// {
		// targetFile = new File(targetFile, simpleName);
		// }
		try {
			// target = new FileOutputStream(targetFile);
			byte[] buffer = new byte[BUFF_SIZE];
			int byteNum;

			while ((byteNum = in.read(buffer)) != NEGATIVE_ONE) {
				target.write(buffer, 0, byteNum);

			}
			System.out.println("[SystemUtil:copyFile]:file copy successfully!");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				in.close();
				in = null;
			}
			if (target != null) {
				target.close();
				target = null;
			}
		}
	}

	/**
	 * 
	 * @param fullpath
	 *            :/a/b/c/d
	 * @return /a/b/c/
	 */
	public static String getParentDir(String fullpath) {
		// String parentDir = null;
		if (ValueWidget.isNullOrEmpty(fullpath)) {
			System.out.println("The first argument can not be null");
			return null;
		}

		// if (fullpath.contains("/")) {
		// int index=fullpath.lastIndexOf("/") ;
		// parentDir = fullpath.substring(0, index+ 1);
		// }
		return new File(fullpath).getParent();
	}

	/**
	 * 
	 * @param fullpath
	 *            :/a/b/c/d
	 * @return d
	 */
	public static String getFileSimpleName(String fullpath) {
		// String parentDir = null;
		if (null == fullpath) {
			System.out.println("The first argument can not be null");
			return null;
		}
		// if (fullpath.contains("/")) {
		// parentDir = fullpath.substring(fullpath.lastIndexOf("/") + 1);
		// }
		return new File(fullpath).getName();
	}

	// public static void main(String[] args) throws IOException
	// {
	// copyFile("/home/whuang2/study/linux/study/c/main.exe", "/home/whuang2");
	// }
	public static String convertUTF2ISO(String oldName) {
		if (oldName == null) {
			return oldName;
		}
		try {
			return new String(oldName.getBytes(CHARSET_UTF), CHARSET_ISO88591);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String convertGBK2ISO(String input) {
		if (input == null) {
			return input;
		}
		try {
			return new String(input.getBytes(CHARSET_GBK), CHARSET_ISO88591);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}

	/***
	 * convert GBK to UTF-8
	 * 
	 * @param input
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static byte[] convertGBK2UTF(byte[] input)
			throws UnsupportedEncodingException {
		return new String(input, SystemUtil.CHARSET_GBK)
				.getBytes(SystemUtil.CHARSET_UTF);
	}

	public static byte[] convertFromeGBK(byte[] input, String toCharset)
			throws UnsupportedEncodingException {
		return new String(input, SystemUtil.CHARSET_GBK).getBytes(toCharset);
	}

	/***
	 * convert utf-8 to gbk
	 * 
	 * @param input
	 * @return
	 */
	public static String convertUTF2GBK(String input) {
		if (input == null) {
			return input;
		}
		try {
			return new String(input.getBytes(CHARSET_UTF), CHARSET_GBK);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String convertISO2UTF(String oldName) {
		if (oldName == null) {
			return oldName;
		}
		try {
			return new String(oldName.getBytes(CHARSET_ISO88591), CHARSET_UTF);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String convertISO2GBK(String input) {
		if (input == null) {
			return input;
		}
		try {
			return new String(input.getBytes(CHARSET_ISO88591), CHARSET_GBK);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void printFilesSimpleName(File[] files) {
		for (File file : files) {
			System.out.println(file.getName());
		}
	}

	public static void printFilesFilePath(File[] files) {
		for (File file : files) {
			System.out.println(file.getAbsolutePath());
		}
	}

	/***
	 * 
	 * @param srcfile
	 *            : source file
	 * @param targfile
	 *            : target file
	 * @param inputCharset
	 *            : from charset
	 * @param outputCharset
	 *            : to charset
	 */
	public static void convertEncoding(File srcfile, File targfile,
			String inputCharset, String outputCharset) {
		FileInputStream fin = null;
		FileOutputStream fout = null;
		char[] cbuf = new char[BUFF_SIZE];
		int size_char;
		try {
			fin = new FileInputStream(srcfile);
			fout = new FileOutputStream(targfile);
			InputStreamReader isr = null;
			OutputStreamWriter osw = null;
			try {
				isr = new InputStreamReader(fin, inputCharset);
				osw = new OutputStreamWriter(fout, outputCharset);
				while ((size_char = isr.read(cbuf)) != NEGATIVE_ONE) {
					osw.write(cbuf, 0, size_char);
				}
				//
			} catch (UnsupportedEncodingException e1) {
				e1.printStackTrace();
			} catch (IOException e1) {
				e1.printStackTrace();
			} finally {
				try {
					isr.close();
					osw.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}

			}

		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		} finally {
			try {
				if (fin != null) {
					fin.close();
				}
				if (fout != null) {
					fout.close();
				}
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
	}

	/**
	 * delete the same one
	 * 
	 * @param list
	 * @return
	 */
	public static List<String> guolv(List<String> list) {
		List<String> newlist = new ArrayList<String>();
		if (list != null && list.size() > 0) {
			newlist.add(list.get(0));
			for (int i = 1; i < list.size(); i++) {
				if (!newlist.contains(list.get(i))) {
					newlist.add(list.get(i));
				}
			}
		}
		return newlist;
	}

	/***
	 * delete CRLF; delete empty line ;delete blank lines
	 * 
	 * @param input
	 * @return
	 */
	private static String deleteCRLFOnce(String input) {
		if (ValueWidget.isHasValue(input)) {
			return input.replaceAll("((\r\n)|\n)[\\s\t ]*(\\1)+", "$1")
					.replaceAll("^((\r\n)|\n)", "");
		} else {
			return null;
		}
	}

	/***
	 * Delete all spaces
	 * 
	 * @param input
	 * @return
	 */
	public static String deleteAllCRLF(String input) {
		return input.replaceAll("((\r\n)|\n)[\\s\t ]*", "").replaceAll(
				"^((\r\n)|\n)", "");
	}

	/**
	 * delete CRLF; delete empty line ;delete blank lines
	 * 
	 * @param input
	 * @return
	 */
	public static String deleteCRLF(String input) {
		input = SystemUtil.deleteCRLFOnce(input);
		return SystemUtil.deleteCRLFOnce(input);
	}

	/***
	 * Use uniqueness of collection
	 * 
	 * @param list
	 * @return
	 */
	public static List<String> guolv2(List<String> list) {
		Set<String> set = new HashSet<String>(list);
		return new ArrayList<String>(set);
	}

	/**
	 * delete the same one
	 * 
	 * @param list
	 * @return
	 */
	public static List<Integer> guolvInteger(List<Integer> list) {
		List<Integer> newlist = new ArrayList<Integer>();
		if (list != null && list.size() > 0) {
			newlist.add(list.get(0));
			for (int i = 1; i < list.size(); i++) {
				if (!newlist.contains(list.get(i))) {
					newlist.add(list.get(i));
				}
			}
		}
		return newlist;
	}

	public static List<Integer> guolvInteger2(List<Integer> list) {
		Set<Integer> set = new HashSet<Integer>(list);
		return new ArrayList<Integer>(set);
	}

	/**
	 * 字节数大于1,则返回true
	 * 
	 * @param c
	 * @return
	 */
	public static boolean isChinese(char c) {
		return String.valueOf(c).getBytes().length > 1;
	}

	/**
	 * 判断str 中的所有字符是否全部是中文字符(包括中文的标点符号)
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isAllChinese(String str) {
		char[] cs = null;
		if (str.length() == 1) {
			cs = new char[1];
			cs[0] = str.charAt(0);
		} else {
			cs = str.toCharArray();
		}
		for (int i = 0; i < cs.length; i++) {
			char c = cs[i];
			if (!isChinese(c)) {
				return false;
			}
		}
		return true;
	}

	public static boolean isHasChinses(String str) {
		String encodeName = "UTF-8";
		for (int i = 0; i < str.length(); i++) {
			try {
				String singleStr = str.substring(i, i + 1);
				int leng = getEncodeLength(singleStr, encodeName);
				// System.out.println(singleStr + "\t" + leng);
				if (leng == 9)// 表示是中文字符
				{
					// System.out.println("有中文");
					return true;
				}
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (MyException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return false;
	}

	public static boolean isHasChinses2(String str) {
		String encodeName = "UTF-8";
		char[] chars = str.toCharArray();
		for (int i = 0; i < chars.length; i++) {
			try {
				char c = chars[i];
				int leng = getEncodeLength(c, encodeName);
				// System.out.println(singleStr + "\t" + leng);
				if (leng == 9)// 表示是中文字符
				{
					// System.out.println("有中文");
					return true;
				}
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (MyException e) {
				e.printStackTrace();
			}
		}
		return false;
	}

	public static int getEncodeLength(String str, String encodeName)
			throws Exception, UnsupportedEncodingException {// 返回值为9 的话,则说明有中文。
		if (str.length() != 1) {
			throw new Exception("超过一个字符");
		}
		String encod = URLEncoder.encode(str, "UTF-8");
		return encod.length();
	}

	public static int getEncodeLength(char c, String encodeName)
			throws MyException, UnsupportedEncodingException {// 返回值为9
		// 的话,则说明有中文。
		String encod = URLEncoder.encode(String.valueOf(c), "UTF-8");
		return encod.length();
	}

	/**
	 * 删除input字符串中的html格式
	 * 
	 * @param input
	 * @param length
	 *            显示的字符的个数
	 * @return
	 */
	public static String splitAndFilterString(String input, int length) {
		if (input == null || input.trim().equals("")) {
			return "";
		}
		// 去掉所有html元素,
		String str = input.replaceAll("\\&[a-zA-Z]{1,10};", "").replaceAll(
				"<[^>]*>", "");
		str = str.replaceAll("[(/>)<]", "");
		int len = str.length();
		if (len <= length) {
			return str;
		} else {
			str = str.substring(0, length);
			str += "......";
		}
		return str;
	}

	/**
	 * 返回纯文本,去掉html的所有标签,并且去掉空行
	 * 
	 * @param input
	 * @return
	 */
	public static String splitAndFilterString(String input) {
		if (input == null || input.trim().equals("")) {
			return "";
		}
		// 去掉所有html元素,
		String str = input.replaceAll("\\&[a-zA-Z]{1,10};", "").replaceAll(
				"<[^>]*>", "");
		str = str.replaceAll("[(/>)<]", "");
		return SystemUtil.deleteCRLF(str);
	}

	public static boolean contains(List<Object> list, Object value) {
		if (list == null || list.size() == 0) {
			return false;
		} else {
			for (int i = 0; i < list.size(); i++) {
				String valueStr;
				if (value instanceof File) {
					valueStr = ((File) value).getName();
				} else {
					valueStr = value.toString();
				}
				Object obj = list.get(i);
				if (obj instanceof File) {
					if (list.contains(valueStr)
							|| ((File) obj).getName().toString()
									.equals(valueStr)) {
						return true;
					}
				} else {
					if (list.contains(valueStr)
							|| list.get(i).toString().equals(valueStr)) {
						return true;
					}
				}
			}
		}
		return false;
	}

	/**
	 * minus Set
	 * 
	 * @param oldList
	 * @param list
	 * @return
	 */
	public static List<Object> getMinusSet(List oldList, List list) {
		List selectedList = null;
		if (oldList != null) {
			selectedList = new ArrayList<Object>();
			int leng = oldList.size();
			if (leng != 0) {
				for (int i = 0; i < leng; i++) {
					Object obj = oldList.get(i);
					if (!contains(list, obj)) {
						selectedList.add(obj);
					}
				}
			}
		}
		return selectedList;
	}

	public static List<File> getMinusSetFile(List oldList, List list) {
		List selectedList = null;
		if (oldList != null) {
			selectedList = new ArrayList<File>();
			int leng = oldList.size();
			if (leng != 0) {
				for (int i = 0; i < leng; i++) {
					Object obj = oldList.get(i);
					if (!contains(list, obj)) {
						selectedList.add(obj);
					}
				}
			}
		}
		return selectedList;
	}

	public static List<String> getMinusSetStr(List oldList, List list) {
		List selectedList = null;
		if (oldList != null) {
			selectedList = new ArrayList<Object>();
			int leng = oldList.size();
			if (leng != 0) {
				for (int i = 0; i < leng; i++) {
					Object obj = oldList.get(i);
					if (!contains(list, obj)) {
						selectedList.add(obj);
					}
				}
			}
		}
		return selectedList;
	}

	/**
	 * Get MD5 of one file:hex string,test OK!
	 * 
	 * @param file
	 * @return
	 */
	public static String getFileMD5(File file) {
		if (!file.exists() || !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)) != NEGATIVE_ONE) {
				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);
	}

	/***
	 * Get MD5 of one file!test ok!
	 * 
	 * @param filepath
	 * @return
	 */
	public static String getFileMD5(String filepath) {
		File file = new File(filepath);
		return getFileMD5(file);
	}

	/**
	 * MD5 encrypt,test ok
	 * 
	 * @param data
	 * @return byte[]
	 * @throws Exception
	 */
	public static byte[] encryptMD5(byte[] data) throws Exception {

		MessageDigest md5 = MessageDigest.getInstance(SystemUtil.KEY_MD5);
		md5.update(data);
		return md5.digest();
	}

	public static byte[] encryptMD5(String data) throws Exception {
		return encryptMD5(data.getBytes(SystemUtil.CHARSET_ISO88591));
	}

	/***
	 * compare two file by Md5
	 * 
	 * @param file1
	 * @param file2
	 * @return
	 */
	public static boolean isSameMd5(File file1, File file2) {
		String md5_1 = SystemUtil.getFileMD5(file1);
		String md5_2 = SystemUtil.getFileMD5(file2);
		return md5_1.equals(md5_2);
	}

	/***
	 * compare two file by Md5
	 * 
	 * @param filepath1
	 * @param filepath2
	 * @return
	 */
	public static boolean isSameMd5(String filepath1, String filepath2) {
		File file1 = new File(filepath1);
		File file2 = new File(filepath2);
		return isSameMd5(file1, file2);
	}

	/***
	 * the times target occur in <code>int[] ints</code>
	 * 
	 * @param ints
	 * @param target
	 * @return
	 */
	public static int count(int[] ints, int target) {
		int count = 0;
		for (int i = 0; i < ints.length; i++) {
			if (ints[i] == target) {
				count++;
			}
		}
		return count;
	}

	/***
	 * Ignore Case
	 * 
	 * @param strs
	 * @param target
	 * @return
	 */
	public static int count(String[] strs, String target) {
		int count = 0;
		for (int i = 0; i < strs.length; i++) {
			if (strs[i].equalsIgnoreCase(target)) {
				count++;
			}
		}
		return count;
	}

	/***
	 * Ignore Case
	 * 
	 * @param list
	 * @param target
	 * @return
	 */
	public static int count(List<String> list, String target) {
		int count = 0;
		for (int i = 0; i < list.size(); i++) {
			if (list.get(i).equalsIgnoreCase(target)) {
				count++;
			}
		}
		return count;
	}

	// public static void printSet(Set<Integer>set ){
	// for(Iterator<Integer> it=set.iterator();it.hasNext();){
	// Integer age=it.next();
	// System.out.println(age);
	// }
	// }

	/***
	 * 
	 * @param list
	 */
	public static void printList(List<?> list, boolean isNewline,
			String delimiter) {
		for (int i = 0; i < list.size(); i++) {
			Object obj = list.get(i);
			if (isNewline) {
				System.out.println(obj);
			} else {
				System.out.print(obj + delimiter);
			}
		}
	}

	public static void printList(List<?> list, String delimiter) {
		printList(list, true, delimiter);
	}

	public static void printStrList(List<String> list) {
		for (int i = 0; i < list.size(); i++) {
			System.out.println(list.get(i));
		}
	}

	public static void printSet(Set<Object> set) {
		for (Iterator<Object> it = set.iterator(); it.hasNext();) {
			Object age = it.next();
			System.out.println(age);
		}
	}

	public static <T extends Serializable> T clone2(T obj) {
		T clonedObj = null;
		try {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			ObjectOutputStream oos = new ObjectOutputStream(baos);
			oos.writeObject(obj);
			oos.close();
			ByteArrayInputStream bais = new ByteArrayInputStream(
					baos.toByteArray());
			ObjectInputStream ois = new ObjectInputStream(bais);
			clonedObj = (T) ois.readObject();
			ois.close();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return clonedObj;
	}

	/***
	 * convert byte array to public key algorithm : RSA
	 * 
	 * @param keyBytes
	 *            byte[]
	 * @return RSAPublicKey
	 * @throws Exception
	 */
	public static PublicKey convert2PublicKey(byte[] keyBytes) throws Exception {
		X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory
				.getInstance(SystemUtil.KEY_ALGORITHM_RSA);// RSA
		PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);
		return publicKey;
	}

	/***
	 * 
	 * @param keyHexStr
	 *            : hex(16) string
	 * @return PublicKey
	 * @throws Exception
	 */
	public static PublicKey convert2PublicKey(String keyHexStr)
			throws Exception {
		byte[] keyBytes = toBytes(keyHexStr);
		return convert2PublicKey(keyBytes);
	}

	/**
	 * convert public key to hex(16) bit string
	 * 
	 * @param publicKey
	 * @return hex(16) bit string
	 */
	public static String convert4PublicKey(PublicKey publicKey) {
		return toHexString(publicKey.getEncoded());
	}

	public static PublicKey getPublicKey(InputStream in)
			throws CertificateException {
		CertificateFactory cf = CertificateFactory
				.getInstance(SystemUtil.CERTIFICATEFACTORY_X509);
		X509Certificate oCertServer = (X509Certificate) cf
				.generateCertificate(in);
		PublicKey pubKey = oCertServer.getPublicKey();
		return pubKey;
	}

	/***
	 * 
	 * @param hex
	 *            :hex(16) bit string
	 * @return PublicKey
	 * @throws CertificateException
	 */
	public static PublicKey getPublicKey(String hex)
			throws CertificateException {
		InputStream in = FileUtils.getInputSream2hexString(hex);
		return getPublicKey(in);
	}

	/***
	 * 
	 * @param modulus
	 *            :N
	 * @param publicExponent
	 *            :E
	 * @return
	 * @throws Exception
	 */
	public static PublicKey getPublicKey(String modulus, String publicExponent)
			throws Exception {
		BigInteger m = new BigInteger(modulus);

		BigInteger e = new BigInteger(publicExponent);
		RSAPublicKeySpec keySpec = new RSAPublicKeySpec(m, e);
		KeyFactory keyFactory = KeyFactory
				.getInstance(SystemUtil.KEY_ALGORITHM_RSA);

		PublicKey publicKey = keyFactory.generatePublic(keySpec);
		return publicKey;
	}

	// public static PublicKey getPublicKey(BigInteger m, BigInteger e){
	// RSAPublicKeySpec keySpec = new RSAPublicKeySpec(m, e);
	// KeyFactory keyFactory = KeyFactory
	// .getInstance(SystemUtil.KEY_ALGORITHM_RSA);
	//
	// PublicKey publicKey = keyFactory.generatePublic(keySpec);
	// return publicKey;
	// }
	/***
	 * 
	 * @param modulus
	 * @param ePublicExponent
	 * @return
	 * @throws Exception
	 */
	public static PublicKey getPublicKey(BigInteger modulus,
			BigInteger ePublicExponent) throws Exception {
		RSAPublicKeySpec keySpec = new RSAPublicKeySpec(modulus,
				ePublicExponent);
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		PublicKey publicKey = keyFactory.generatePublic(keySpec);

		return publicKey;

	}

	/***
	 * 
	 * @param m
	 * @param publicExponent
	 * @return
	 * @throws Exception
	 */
	public static PublicKey getPublicKey(BigInteger m, byte[] publicExponent)
			throws Exception {
		BigInteger e = new BigInteger(publicExponent);
		return getPublicKey(m, e);
	}

	/**
	 * convert byte array to private key algorithm : RSA
	 * 
	 * @param keyBytes
	 *            byte[]
	 * @return RSAPrivateKey
	 * @throws Exception
	 */
	public static PrivateKey convert2PrivateKey(byte[] keyBytes)
			throws Exception {
		PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory
				.getInstance(SystemUtil.KEY_ALGORITHM_RSA);// RSA
		PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
		return privateKey;
	}

	/***
	 * 
	 * @param keyString
	 *            : hex(16) string
	 * @return
	 * @throws Exception
	 */
	public static PrivateKey convert2PrivateKey(String keyString)
			throws Exception {
		byte[] keyBytes = toBytes(keyString);
		return convert2PrivateKey(keyBytes);
	}

	/***
	 * convert private key to hex bit string
	 * 
	 * @param privateKey
	 * @return keyString : hex(16) string
	 */
	public static String convert4PrivateKey(PrivateKey privateKey) {
		return toHexString(privateKey.getEncoded());
	}

	/**
	 * decrypt,key can be a public key, can also be a private key algorithm :
	 * RSA
	 * 
	 * @param message
	 * @return
	 * @throws Exception
	 */
	public static byte[] decrypt(byte[] message, Key key) throws Exception {
		Cipher cipher = Cipher.getInstance(SystemUtil.KEY_ALGORITHM_RSA);
		cipher.init(Cipher.DECRYPT_MODE, key);
		return cipher.doFinal(message);
	}

	/**
	 * decrypt,key can be a public key, can also be a private key
	 * 
	 * @param message
	 * @return
	 * @throws Exception
	 */
	public static byte[] decrypt(String message, Key key) throws Exception {
		return SystemUtil.decrypt(SystemUtil.toBytes(message), key);
	}

	/**
	 * 解密<br>
	 * 用私钥解密
	 * 
	 * @param data
	 * @param publicKeyStr
	 * @return
	 * @throws Exception
	 */
	public static byte[] decryptByPublicKey(byte[] data, String publicKeyStr)
			throws Exception {
		// 对密钥解密
		byte[] keyBytes = SystemUtil.toBytes(publicKeyStr);

		// 取得公钥
		PublicKey publicKey = SystemUtil.convert2PublicKey(keyBytes);

		return SystemUtil.decrypt(data, publicKey);
	}

	/**
	 * decrypt use private key to decrypt http://www.5a520.cn
	 * http://www.feng123.com
	 * 
	 * @param data
	 * @param privateKeyStr
	 * @return
	 * @throws Exception
	 */
	public static byte[] decryptByPrivateKey(byte[] data, String privateKeyStr)
			throws Exception {
		byte[] keyBytes = SystemUtil.toBytes(privateKeyStr);
		return decryptByPrivateKey(data, keyBytes);
	}

	public static byte[] decryptByPrivateKey(byte[] data, byte[] keyBytes)
			throws Exception {
		PrivateKey privateKey = SystemUtil.convert2PrivateKey(keyBytes);
		return SystemUtil.decrypt(data, privateKey);
	}

	/***
	 * 
	 * @param data
	 * @param N
	 *            :modulus
	 * @param D
	 *            :private exponent
	 * @return
	 * @throws Exception
	 */
	public static byte[] decryptByPrivateKey(byte[] data, byte[] N, byte[] D)
			throws Exception {
		PrivateKey privateKey = getPrivateKey(N, D);
		return decrypt(data, privateKey);
	}

	/***
	 * 
	 * @param dataHex
	 *            :hex bit string
	 * @param privateKeyStr
	 * @param charSet
	 * @return
	 * @throws UnsupportedEncodingException
	 * @throws Exception
	 */
	public static byte[] decryptByPrivateKey(String dataHex,
			String privateKeyStr) throws UnsupportedEncodingException,
			Exception {
		return decryptByPrivateKey(SystemUtil.toBytes(dataHex), privateKeyStr);
	}

	/**
	 * DES
	 * 
	 * @param data
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static byte[] decryptDES(byte[] data, byte[] key) throws Exception {
		// Generate a random number generator which can be trusted
		SecureRandom sr = new SecureRandom();

		DESKeySpec dks = new DESKeySpec(key);

		// Create a key factory, and then use it to convert DESKeySpec to
		// SecretKey
		SecretKeyFactory keyFactory = SecretKeyFactory
				.getInstance(SystemUtil.KEY_ALGORITHM_DES);
		SecretKey securekey = keyFactory.generateSecret(dks);
		Cipher cipher = Cipher.getInstance(SystemUtil.KEY_ALGORITHM_DES);

		cipher.init(Cipher.DECRYPT_MODE, securekey, sr);

		return cipher.doFinal(data);
	}

	/**
	 * DES
	 * 
	 * @param data
	 * @param key
	 * @return
	 * @throws IOException
	 * @throws Exception
	 */
	public static String decryptDES(String data, String key)
			throws IOException, Exception {
		if (data =http://www.mamicode.com/= null)>

package com.common.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

import com.string.widget.util.RandomUtils;

/**
 * Description User: I8800
 */
public class ZipUtil {

	/**
	 * 获得zip压缩包中文件数(包括目录)
	 * 
	 * @param zipFile
	 * @return
	 */
	public static int getFiles(final ZipFile zipFile) {
		return zipFile.size();
	}

	/**
	 * 获得zip压缩包二进制数组中文件数(包括目录)
	 * 
	 * @param zipBytes
	 * @return
	 * @throws IOException
	 */
	public static int getFiles(final byte[] zipBytes) throws IOException {
		int files = 0;
		ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
				zipBytes);
		ZipInputStream zipInputStream = new ZipInputStream(byteArrayInputStream);
		while (zipInputStream.getNextEntry() != null) {
			files++;
		}
		zipInputStream.closeEntry();
		zipInputStream.close();
		byteArrayInputStream.close();
		return files;
	}

	/**
	 * 获得zip压缩包中文件数(包括目录)
	 * 
	 * @param filename
	 * @return
	 * @throws IOException
	 */
	public static int getFiles(final String filename) throws IOException {
		ZipFile zipFile = new ZipFile(filename);
		int files = getFiles(zipFile);
		zipFile.close();
		return files;
	}

	/**
	 * 获得zip压缩包中文件数(包括目录)
	 * 
	 * @param file
	 * @return
	 * @throws IOException
	 */
	public static int getFiles(final File file) throws IOException {
		ZipFile zipFile = new ZipFile(file);
		int files = getFiles(zipFile);
		zipFile.close();
		return files;
	}

	/**
	 * 从zip包中读取给定文件名的内容
	 * 
	 * @param zipFilename
	 * @param name
	 *            获得内容的文件全文件名 注:大小写敏感
	 * @return
	 * @throws IOException
	 */
	public static byte[] getContent(final String zipFilename, final String name)
			throws IOException {
		ZipFile zipFile = new ZipFile(zipFilename);
		byte[] bytes = getContent(zipFile, name);
		zipFile.close();
		return bytes;
	}

	/**
	 * 从zip包中读取给定文件名的内容
	 * 
	 * @param file
	 * @param name
	 *            获得内容的文件全文件名 注:大小写敏感
	 * @return
	 * @throws IOException
	 */
	public static byte[] getContent(final File file, final String name)
			throws IOException {
		ZipFile zipFile = new ZipFile(file);
		byte[] bytes = getContent(zipFile, name);
		zipFile.close();
		return bytes;
	}

	/**
	 * 从zip包中读取给定文件名的内容
	 * 
	 * @param zipFile
	 * @param name
	 *            获得内容的文件全文件名 注:大小写敏感
	 * @return
	 * @throws IOException
	 */
	public static byte[] getContent(final ZipFile zipFile, final String name)
			throws IOException {
		ZipEntry zipEntry = zipFile.getEntry(name);
		return getContent(zipFile, zipEntry);
	}

	/**
	 * 从zip包中读取给定文件名的内容
	 * 
	 * @param zipFile
	 * @param zipEntry
	 * @return
	 * @throws IOException
	 */
	public static byte[] getContent(final ZipFile zipFile,
			final ZipEntry zipEntry) throws IOException {
		InputStream inputStream = zipFile.getInputStream(zipEntry);
		byte[] buffer = new byte[1024];
		byte[] bytes = new byte[0];
		int length;
		while ((length = (inputStream.read(buffer))) != -1) {
			byte[] readBytes = new byte[length];
			System.arraycopy(buffer, 0, readBytes, 0, length);
			bytes = SystemUtil.mergeArray(bytes, readBytes);
		}
		inputStream.close();
		return bytes;
	}

	/**
	 * 从二进制zip包byte数组中获取给定文件名的内容
	 * 
	 * @param zipBytes
	 * @param name
	 * @return
	 * @throws IOException
	 * @throws InterruptedException
	 */
	public static byte[] getContent(final byte[] zipBytes, final String name)
			throws IOException, InterruptedException {
		File file = File.createTempFile(RandomUtils.getTimeRandom(), "."
				+ "zip");
		FileOutputStream fileOutputStream = new FileOutputStream(file);
		fileOutputStream.write(zipBytes);
		fileOutputStream.flush();
		fileOutputStream.close();
		byte[] bytes = getContent(file, name);
		file.delete();
		return bytes;
	}

	/**
	 * @param zipFilename
	 * @param filename
	 * @throws IOException
	 */
	public static void add(final String zipFilename, final String filename)
			throws IOException {
		File zipFile = new File(zipFilename);
		File file = new File(filename);
		add(zipFile, file);
	}

	/**
	 * @param zipFile
	 * @param file
	 * @throws IOException
	 */
	public static void add(final File zipFile, final File file)
			throws IOException {
		FileInputStream fileInputStream = new FileInputStream(file);
		int length = fileInputStream.available();
		byte[] bytes = new byte[length];
		fileInputStream.read(bytes);
		fileInputStream.close();
		add(zipFile, file.getName(), bytes);
	}

	/**
	 * @param zipFile
	 * @param filename
	 * @param bytes
	 * @throws IOException
	 */
	public static void add(final File zipFile, final String filename,
			final byte[] bytes) throws IOException {
		ZipFile zip = new ZipFile(zipFile);
		Enumeration entries = zip.entries();
		FileOutputStream outputStream = new FileOutputStream(zipFile, true);
		ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
		while (entries.hasMoreElements()) {
			ZipEntry entry = (ZipEntry) entries.nextElement();
			addEntry(zipOutputStream, entry,
					getContent(zipFile, entry.getName()));
		}
		ZipEntry zipEntry = new ZipEntry(filename);
		addEntry(zipOutputStream, zipEntry, bytes);

		zipOutputStream.flush();
		zipOutputStream.close();

		outputStream.flush();
		outputStream.close();
		zip.close();
	}

	/**
	 * @param zipFile
	 * @param filename
	 * @throws IOException
	 */
	public static void delete(final File zipFile, final String filename)
			throws IOException {
		ZipFile zip = new ZipFile(zipFile);
		Enumeration entries = zip.entries();
		FileOutputStream outputStream = new FileOutputStream(zipFile, true);
		ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
		while (entries.hasMoreElements()) {
			ZipEntry entry = (ZipEntry) entries.nextElement();
			if (!entry.getName().equalsIgnoreCase(filename)) {
				addEntry(zipOutputStream, entry,
						getContent(zipFile, entry.getName()));
			}
		}
		zipOutputStream.flush();
		zipOutputStream.close();

		outputStream.flush();
		outputStream.close();
		zip.close();
	}

	/**
	 * 添加单个ZipEntry
	 * 
	 * @param zipOutputStream
	 * @param zipEntry
	 * @param bytes
	 * @throws IOException
	 */
	private static void addEntry(ZipOutputStream zipOutputStream,
			ZipEntry zipEntry, byte[] bytes) throws IOException {
		zipOutputStream.putNextEntry(zipEntry);
		zipOutputStream.write(bytes);
		zipOutputStream.flush();
		zipOutputStream.closeEntry();
	}

	/**
	 * 获得zip包中的文件名列表
	 * 
	 * @param zipFile
	 * @return
	 */
	public static List<String> list(final ZipFile zipFile) {
		List<String> list = new ArrayList<String>();
		Enumeration zipEntries = zipFile.entries();
		while (zipEntries.hasMoreElements()) {
			ZipEntry entry = (ZipEntry) zipEntries.nextElement();
			list.add(entry.getName());
		}
		return list;
	}

	/**
	 * 获得zip包中的文件名列表
	 * 
	 * @param file
	 * @return
	 */
	public static List<String> list(final File file) throws IOException {
		ZipFile zipFile = new ZipFile(file);
		List<String> filenameList = list(zipFile);
		zipFile.close();
		return filenameList;
	}

	public static InputStream getInputStreamFromZip(final ZipFile zipFile,
			final String name) throws IOException {
		ZipEntry zipEntry = zipFile.getEntry(name);
		InputStream inputStream = zipFile.getInputStream(zipEntry);
		return inputStream;
	}

	/***
	 * 
	 * @param zipFilename
	 * @param name
	 * @return InputStream
	 * @throws IOException
	 */
	public static InputStream getInputStreamFromZip(final String zipFilename,
			final String name) throws IOException {
		ZipFile zipFile = new ZipFile(zipFilename);
		return getInputStreamFromZip(zipFile, name);
	}

	public static InputStream getInputStreamFromZip(final File file,
			final String name) throws ZipException, IOException {
		ZipFile zipFile = new ZipFile(file);
		return getInputStreamFromZip(zipFile, name);
	}

	/**
	 * 获得zip包中的文件名列表
	 * 
	 * @param filename
	 * @return
	 * @throws IOException
	 */
	public static List<String> list(final String filename) throws IOException {
		File file = new File(filename);
		return list(file);
	}

	/**
	 * 把源文件夹压缩成zip包
	 * 
	 * @param zipFile
	 * @param srcFolder
	 * @throws IOException
	 */
	public static void compress(final File zipFile, final String srcFolder)
			throws IOException {
		File folder = new File(srcFolder);
		FileOutputStream fileOutputStream = new FileOutputStream(zipFile);
		BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(
				fileOutputStream);
		ZipOutputStream zipOutputStream = new ZipOutputStream(
				bufferedOutputStream);
		if (!folder.isDirectory()) {
			compress(zipOutputStream, folder, srcFolder);
		} else {
			List<String> filenameList = listFilename(srcFolder);
			for (String filename : filenameList) {
				File file = new File(filename);
				compress(zipOutputStream, file, srcFolder);
			}
		}
		zipOutputStream.flush();
		zipOutputStream.close();
		bufferedOutputStream.flush();
		bufferedOutputStream.close();
		fileOutputStream.flush();
		fileOutputStream.close();
	}

	/**
	 * @param zipOutputStream
	 * @param file
	 * @throws IOException
	 */
	private static void compress(final ZipOutputStream zipOutputStream,
			final File file, final String srcFolder) throws IOException {
		FileInputStream fileInputStream = new FileInputStream(file);
		BufferedInputStream bufferedInputStream = new BufferedInputStream(
				fileInputStream, 1024);
		ZipEntry entry = new ZipEntry(file.getPath().substring(
				srcFolder.length() + 1));
		zipOutputStream.putNextEntry(entry);
		byte[] data = http://www.mamicode.com/new byte[bufferedInputStream.available()];>
import java.io.IOException;

public class ProcessUtil
{
    private static Process process = null;
    static
    {

    }
    private ProcessUtil()
    {
        throw new Error("Don't let anyone instantiate this class.");
    }

    public static Process getPro(String command) throws IOException
    {
        process = Runtime.getRuntime().exec(command);
        return process;
    }

    public static Process getPro(String[] command) throws IOException
    {
        process = Runtime.getRuntime().exec(command);
        return process;
    }
}