자바 클래식 코드

46676 단어 자바
package com.common.file;

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.OutputStream;
import java.text.DateFormat;
import java.util.Date;
import java.util.Iterator;

import javax.swing.text.html.HTMLDocument.HTMLReader.FormAction;

/**
 * 
 *     :
 * 
 * @author Administrator
 * @Date Jul 19, 2008
 * @Time 9:46:11 AM
 * @version 1.0
 */
public class FileUtil {

	/**
	 *     :                 ,         
	 * 
	 * @param path
	 *               
	 */
	public static void list(File path) {
		if (!path.exists()) {
			System.out.println("       !");
		} else {
			if (path.isFile()) {
				if (path.getName().toLowerCase().endsWith(".pdf")
						|| path.getName().toLowerCase().endsWith(".doc")
						|| path.getName().toLowerCase().endsWith(".chm")
						|| path.getName().toLowerCase().endsWith(".html")
						|| path.getName().toLowerCase().endsWith(".htm")) {//     
					System.out.println(path);
					System.out.println(path.getName());
				}
			} else {
				File[] files = path.listFiles();
				for (int i = 0; i < files.length; i++) {
					list(files[i]);
				}
			}
		}
	}

	/**
	 *     :                ,               
	 * 
	 * @param source
	 *               
	 * @param target
	 *                  
	 * @return void
	 */
	public static void copy(File source, File target) {
		File tarpath = new File(target, source.getName());
		if (source.isDirectory()) {
			tarpath.mkdir();
			File[] dir = source.listFiles();
			for (int i = 0; i < dir.length; i++) {
				copy(dir[i], tarpath);
			}
		} else {
			try {
				InputStream is = new FileInputStream(source); //             
				OutputStream os = new FileOutputStream(tarpath); //              
				byte[] buf = new byte[1024];//             
				int len = 0;
				while ((len = is.read(buf)) != -1) {
					os.write(buf, 0, len);
				}
				is.close();
				os.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		File file = new File("F:\\Tomcat");
		list(file);
		Date myDate = new Date(); 
		DateFormat df = DateFormat.getDateInstance();
		System.out.println(df.format(myDate)); 
	}

}

 
 
package com.common.string;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *     :            
 * 
 * @author Administrator
 * @Date Jul 18, 2008
 * @Time 2:19:47 PM
 * @version 1.0
 */
public class StringUtil {

	/**
	 *     :     
	 * 
	 * @param str
	 *            String      
	 * @param splitsign
	 *            String    
	 * @return String[]          
	 */
	@SuppressWarnings("unchecked")
	public static String[] split(String str, String splitsign) {
		int index;
		if (str == null || splitsign == null) {
			return null;
		}
		ArrayList al = new ArrayList();
		while ((index = str.indexOf(splitsign)) != -1) {
			al.add(str.substring(0, index));
			str = str.substring(index + splitsign.length());
		}
		al.add(str);
		return (String[]) al.toArray(new String[0]);
	}

	/**
	 *     :     
	 * 
	 * @param from
	 *            String      
	 * @param to
	 *            String      
	 * @param source
	 *            String     
	 * @return String        
	 */
	public static String replace(String from, String to, String source) {
		if (source == null || from == null || to == null)
			return null;
		StringBuffer str = new StringBuffer("");
		int index = -1;
		while ((index = source.indexOf(from)) != -1) {
			str.append(source.substring(0, index) + to);
			source = source.substring(index + from.length());
			index = source.indexOf(from);
		}
		str.append(source);
		return str.toString();
	}

	/**
	 *      ,    HTML       (         )
	 * 
	 * @param str
	 *            String      
	 * @return String        
	 */
	public static String htmlencode(String str) {
		if (str == null) {
			return null;
		}
		return replace("\"", "&quot;", replace("<", "&lt;", str));
	}

	/**
	 *      ,           (          )
	 * 
	 * @param str
	 *            String
	 * @return String
	 */
	public static String htmldecode(String str) {
		if (str == null) {
			return null;
		}

		return replace("&quot;", "\"", replace("&lt;", "<", str));
	}

	private static final String _BR = "<br/>";

	/**
	 *     :            ,     ,  ,  ,TAB
	 * 
	 * @param str
	 *            String      
	 * @return String        
	 */
	public static String htmlshow(String str) {
		if (str == null) {
			return null;
		}

		str = replace("<", "&lt;", str);
		str = replace(" ", "&nbsp;", str);
		str = replace("\r
", _BR, str); str = replace("
", _BR, str); str = replace("\t", "&nbsp;&nbsp;&nbsp;&nbsp;", str); return str; } /** * : * * @param str * String * @param length * int * @return String */ public static String toLength(String str, int length) { if (str == null) { return null; } if (length <= 0) { return ""; } try { if (str.getBytes("GBK").length <= length) { return str; } } catch (Exception e) { } StringBuffer buff = new StringBuffer(); int index = 0; char c; length -= 3; while (length > 0) { c = str.charAt(index); if (c < 128) { length--; } else { length--; length--; } buff.append(c); index++; } buff.append("..."); return buff.toString(); } /** * : * * @param str * * @return true, false */ public static boolean isInteger(String str) { Pattern pattern = Pattern.compile("^[-\\+]?[\\d]+$"); return pattern.matcher(str).matches(); } /** * , double float * * @param str * * @return true, false */ public static boolean isDouble(String str) { Pattern pattern = Pattern.compile("^[-\\+]?\\d+\\.\\d+$"); return pattern.matcher(str).matches(); } /** * c */ public static boolean isLetter(String str) { if (str == null || str.length() < 0) { return false; } Pattern pattern = Pattern.compile("[\\w\\.-_]*"); return pattern.matcher(str).matches(); } /** * Email content * * @param content * @return */ public static String parse(String content) { String email = null; if (content == null || content.length() < 1) { return email; } // @ int beginPos; int i; String token = "@"; String preHalf = ""; String sufHalf = ""; beginPos = content.indexOf(token); if (beginPos > -1) { // String s = null; i = beginPos; while (i > 0) { s = content.substring(i - 1, i); if (isLetter(s)) preHalf = s + preHalf; else break; i--; } // i = beginPos + 1; while (i < content.length()) { s = content.substring(i, i + 1); if (isLetter(s)) sufHalf = sufHalf + s; else break; i++; } // email = preHalf + "@" + sufHalf; if (isEmail(email)) { return email; } } return null; } /** * : Email . * * @param str * * @return Email true, false */ public static boolean isEmail(String email) { if (email == null || email.length() < 1 || email.length() > 256) { return false; } Pattern pattern = Pattern .compile("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$"); return pattern.matcher(email).matches(); } /** * : * * @param str * * @return true, false */ public static boolean isChinese(String str) { Pattern pattern = Pattern.compile("[\u0391-\uFFE5]+$"); return pattern.matcher(str).matches(); } /** * : , null "" * * @param str * @return */ public static boolean isBlank(String str) { return str == null || str.trim().length() == 0; } /** * : * * @param x * @return */ public static boolean isPrime(int x) { if (x <= 7) { if (x == 2 || x == 3 || x == 5 || x == 7) return true; } int c = 7; if (x % 2 == 0) return false; if (x % 3 == 0) return false; if (x % 5 == 0) return false; int end = (int) Math.sqrt(x); while (c <= end) { if (x % c == 0) { return false; } c += 4; if (x % c == 0) { return false; } c += 2; if (x % c == 0) { return false; } c += 4; if (x % c == 0) { return false; } c += 2; if (x % c == 0) { return false; } c += 4; if (x % c == 0) { return false; } c += 6; if (x % c == 0) { return false; } c += 2; if (x % c == 0) { return false; } c += 6; } return true; } /** * : * * @param str * * @return String */ public static String hangeToBig(String str) { double value; try { value = Double.parseDouble(str.trim()); } catch (Exception e) { return null; } char[] hunit = { ' ', ' ', ' ' }; // char[] vunit = { ' ', ' ' }; // char[] digit = { ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ' }; // long midVal = (long) (value * 100); // String valStr = String.valueOf(midVal); // String head = valStr.substring(0, valStr.length() - 2); // String rail = valStr.substring(valStr.length() - 2); // String prefix = ""; // String suffix = ""; // // if (rail.equals("00")) { // 0 suffix = " "; } else { suffix = digit[rail.charAt(0) - '0'] + " " + digit[rail.charAt(1) - '0'] + " "; // } // char[] chDig = head.toCharArray(); // char zero = '0'; // '0' 0 byte zeroSerNum = 0; // 0 for (int i = 0; i < chDig.length; i++) { // int idx = (chDig.length - i - 1) % 4; // int vidx = (chDig.length - i - 1) / 4; // if (chDig[i] == '0') { // 0 zeroSerNum++; // 0 if (zero == '0') { // zero = digit[0]; } else if (idx == 0 && vidx > 0 && zeroSerNum < 4) { prefix += vunit[vidx - 1]; zero = '0'; } continue; } zeroSerNum = 0; // 0 if (zero != '0') { // 0, , , prefix += zero; zero = '0'; } prefix += digit[chDig[i] - '0']; // if (idx > 0) prefix += hunit[idx - 1]; if (idx == 0 && vidx > 0) { prefix += vunit[vidx - 1]; // , } } if (prefix.length() > 0) prefix += ' '; // , return prefix + suffix; // } /** * : * * @param str * , * @return String */ @SuppressWarnings("unused") private static String removeSameString(String str) { Set<String> mLinkedSet = new LinkedHashSet<String>();// set : String[] strArray = str.split(" ");// ( ) StringBuffer sb = new StringBuffer(); for (int i = 0; i < strArray.length; i++) { if (!mLinkedSet.contains(strArray[i])) { mLinkedSet.add(strArray[i]); sb.append(strArray[i] + " "); } } System.out.println(mLinkedSet); return sb.toString(); } /** * : * * @param src * @return */ public static String encoding(String src) { if (src == null) return ""; StringBuilder result = new StringBuilder(); if (src != null) { src = src.trim(); for (int pos = 0; pos < src.length(); pos++) { switch (src.charAt(pos)) { case '\"': result.append("&quot;"); break; case '<': result.append("&lt;"); break; case '>': result.append("&gt;"); break; case '\'': result.append("&apos;"); break; case '&': result.append("&amp;"); break; case '%': result.append("&pc;"); break; case '_': result.append("&ul;"); break; case '#': result.append("&shap;"); break; case '?': result.append("&ques;"); break; default: result.append(src.charAt(pos)); break; } } } return result.toString(); } /** * : * * @param handset * @return boolean */ public static boolean isHandset(String handset) { try { String regex = "^1[\\d]{10}$"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(handset); return matcher.matches(); } catch (RuntimeException e) { return false; } } /** * : * * @param src * @return */ public static String decoding(String src) { if (src == null) return ""; String result = src; result = result.replace("&quot;", "\"").replace("&apos;", "\'"); result = result.replace("&lt;", "<").replace("&gt;", ">"); result = result.replace("&amp;", "&"); result = result.replace("&pc;", "%").replace("&ul", "_"); result = result.replace("&shap;", "#").replace("&ques", "?"); return result; } /** * @param args */ public static void main(String[] args) { String source = "abcdefgabcdefgabcdefgabcdefgabcdefgabcdefg"; String from = "efg"; String to = " "; System.out.println(" source , to from, :" + replace(from, to, source)); System.out.println(" :" + toLength("abcdefgabcdefgabcdefgabcdefgabcdefgabcdefg", 9)); System.out.println(" :" + isInteger("+0")); System.out.println(" , double float:" + isDouble("+0.36")); System.out.println(" Email :" + isEmail("[email protected]")); System.out.println(" :" + isChinese(" !")); System.out.println(" :" + isPrime(12)); System.out.println(" :" + hangeToBig("10019658")); System.out.println(" :" + removeSameString("100 100 9658")); System.out.println(" :" + encoding("100\"s<>fdsd100 9658")); System.out.println(" :" + isHandset("15981807340")); System.out.println(" Email:" + parse("159818 [email protected]")); } }

 
 
package com.common.time;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 
 *     :
 * 
 * @author Administrator
 * @Date Jul 19, 2008
 * @Time 9:47:53 AM
 * @version 1.0
 */
public class DateUtil {

	public static Date date = null;

	public static DateFormat dateFormat = null;

	public static Calendar calendar = null;

	/**
	 *     :     
	 * 
	 * @param dateStr
	 *            String      
	 * @param format
	 *            String   
	 * @return Date   
	 */
	public static Date parseDate(String dateStr, String format) {
		try {
			dateFormat = new SimpleDateFormat(format);
			String dt = dateStr.replaceAll("-", "/");
			if ((!dt.equals("")) && (dt.length() < format.length())) {
				dt += format.substring(dt.length()).replaceAll("[YyMmDdHhSs]",
						"0");
			}
			date = (Date) dateFormat.parse(dt);
		} catch (Exception e) {
		}
		return date;
	}

	/**
	 *     :     
	 * 
	 * @param dateStr
	 *            String      :YYYY-MM-DD   
	 * @return Date
	 */
	public static Date parseDate(String dateStr) {
		return parseDate(dateStr, "yyyy/MM/dd");
	}

	/**
	 *     :       
	 * 
	 * @param date
	 *            Date   
	 * @param format
	 *            String   
	 * @return        
	 */
	public static String format(Date date, String format) {
		String result = "";
		try {
			if (date != null) {
				dateFormat = new SimpleDateFormat(format);
				result = dateFormat.format(date);
			}
		} catch (Exception e) {
		}
		return result;
	}

	/**
	 *     :
	 * 
	 * @param date
	 *            Date   
	 * @return
	 */
	public static String format(Date date) {
		return format(date, "yyyy/MM/dd");
	}

	/**
	 *     :    
	 * 
	 * @param date
	 *            Date   
	 * @return     
	 */
	public static int getYear(Date date) {
		calendar = Calendar.getInstance();
		calendar.setTime(date);
		return calendar.get(Calendar.YEAR);
	}

	/**
	 *     :    
	 * 
	 * @param date
	 *            Date   
	 * @return     
	 */
	public static int getMonth(Date date) {
		calendar = Calendar.getInstance();
		calendar.setTime(date);
		return calendar.get(Calendar.MONTH) + 1;
	}

	/**
	 *     :    
	 * 
	 * @param date
	 *            Date   
	 * @return     
	 */
	public static int getDay(Date date) {
		calendar = Calendar.getInstance();
		calendar.setTime(date);
		return calendar.get(Calendar.DAY_OF_MONTH);
	}

	/**
	 *     :    
	 * 
	 * @param date
	 *              
	 * @return     
	 */
	public static int getHour(Date date) {
		calendar = Calendar.getInstance();
		calendar.setTime(date);
		return calendar.get(Calendar.HOUR_OF_DAY);
	}

	/**
	 *     :    
	 * 
	 * @param date
	 *              
	 * @return     
	 */
	public static int getMinute(Date date) {
		calendar = Calendar.getInstance();
		calendar.setTime(date);
		return calendar.get(Calendar.MINUTE);
	}

	/**
	 *     
	 * 
	 * @param date
	 *            Date   
	 * @return     
	 */
	public static int getSecond(Date date) {
		calendar = Calendar.getInstance();
		calendar.setTime(date);
		return calendar.get(Calendar.SECOND);
	}

	/**
	 *     :    
	 * 
	 * @param date
	 *              
	 * @return     
	 */
	public static long getMillis(Date date) {
		calendar = Calendar.getInstance();
		calendar.setTime(date);
		return calendar.getTimeInMillis();
	}

	/**
	 *     :       
	 * 
	 * @param date
	 *              
	 * @return         yyyy/MM/dd   
	 */
	public static String getDate(Date date) {
		return format(date, "yyyy/MM/dd");
	}

	/**
	 *     :       
	 * 
	 * @param date
	 *            Date   
	 * @return         HH:mm:ss   
	 */
	public static String getTime(Date date) {
		return format(date, "HH:mm:ss");
	}

	/**
	 *     :         
	 * 
	 * @param date
	 *            Date   
	 * @return           yyyy/MM/dd HH:mm:ss   
	 */
	public static String getDateTime(Date date) {
		return format(date, "yyyy/MM/dd HH:mm:ss");
	}

	/**
	 *     :    
	 * 
	 * @param date
	 *            Date   
	 * @param day
	 *            int   
	 * @return         
	 */
	public static Date addDate(Date date, int day) {
		calendar = Calendar.getInstance();
		long millis = getMillis(date) + ((long) day) * 24 * 3600 * 1000;
		calendar.setTimeInMillis(millis);
		return calendar.getTime();
	}

	/**
	 *     :    
	 * 
	 * @param date
	 *            Date   
	 * @param date1
	 *            Date   
	 * @return         
	 */
	public static int diffDate(Date date, Date date1) {
		return (int) ((getMillis(date) - getMillis(date1)) / (24 * 3600 * 1000));
	}

	/**
	 *     :          
	 * 
	 * @param strdate
	 *            String      
	 * @return String yyyy-MM-dd   
	 */
	public static String getMonthBegin(String strdate) {
		date = parseDate(strdate);
		return format(date, "yyyy-MM") + "-01";
	}

	/**
	 *     :           
	 * 
	 * @param strdate
	 *            String      
	 * @return String       yyyy-MM-dd  
	 */
	public static String getMonthEnd(String strdate) {
		date = parseDate(getMonthBegin(strdate));
		calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.MONTH, 1);
		calendar.add(Calendar.DAY_OF_YEAR, -1);
		return formatDate(calendar.getTime());
	}

	/**
	 *     :        
	 * 
	 * @param date
	 *            Date   
	 * @return String       yyyy-MM-dd  
	 */
	public static String formatDate(Date date) {
		return formatDateByFormat(date, "yyyy-MM-dd");
	}

	/**
	 *     :            
	 * 
	 * @param date
	 *            Date   
	 * @param format
	 *            String   
	 * @return String      
	 */
	public static String formatDateByFormat(Date date, String format) {
		String result = "";
		if (date != null) {
			try {
				SimpleDateFormat sdf = new SimpleDateFormat(format);
				result = sdf.format(date);
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}

	public static void main(String[] args) {
		Date d = new Date();
		System.out.println(d.toString());
		System.out.println(formatDate(d).toString());
		System.out.println(getMonthBegin(formatDate(d).toString()));
		System.out.println(getMonthBegin("2008/07/19"));
		System.out.println(getMonthEnd("2008/07/19"));
		System.out.println(addDate(d,15).toString());
	}

}

 
 
/*[java]        zip2008 05 28      17:48/*
* Zip.java
*
* Created on 2008 4 2 ,   2:20
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/

package com.founder.mnp.utl;

/**
*
* @author GuoJiale
*/
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


public class ZipUtils {
    static final int BUFFER = 2048;
    
    public static boolean zip( String[] filename ,String outname){
        
        boolean test = true;
        try {
            BufferedInputStream origin = null;
            FileOutputStream dest = new FileOutputStream(outname);
            ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(
                    dest));
            byte data[] = new byte[BUFFER];
            // File f= new File("d:\\111\\");
            //   File files[] = f.listFiles();
            
            for (int i = 0; i < filename.length; i++) {
                File file = new File(filename[i]);
                FileInputStream fi = new FileInputStream(file);
                origin = new BufferedInputStream(fi, BUFFER);
                ZipEntry entry = new ZipEntry(file.getName());
                out.putNextEntry(entry);
                int count;
                while ((count = origin.read(data, 0, BUFFER)) != -1) {
                    out.write(data, 0, count);
                }
                origin.close();
            }
            out.close();
        } catch (Exception e) {
            test = false;
            e.printStackTrace();
        }
        return test;
    }
    
    
    
    public static void main(String argv[]) {
        // File f= new File("d:\\111\\");
        String[] filenames = new String[]{"F:\\12.jpg"};
        zip(filenames,"F:/12.zip");
    }
}
 

 
 
package com.test.test;

/************************************************
MD5    Java Bean
Last Modified:10,Mar,2001
 *************************************************/
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.CRC32;
import java.util.zip.CheckedInputStream;

/*************************************************
 * md5     RSA Data Security, Inc.    IETF  RFC1321  MD5 message-digest   。
 *************************************************/
public class MD5 {
	/*
	 *     S11-S44      44   ,    C     #define    ,          static
	 * final      ,               Instance   
	 */
	private static final int S11 = 7;
	private static final int S12 = 12;
	private static final int S13 = 17;
	private static final int S14 = 22;
	private static final int S21 = 5;
	private static final int S22 = 9;
	private static final int S23 = 14;
	private static final int S24 = 20;
	private static final int S31 = 4;
	private static final int S32 = 11;
	private static final int S33 = 16;
	private static final int S34 = 23;
	private static final int S41 = 6;
	private static final int S42 = 10;
	private static final int S43 = 15;
	private static final int S44 = 21;
	private static final byte[] PADDING = { -128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0 };
	/*
	 *         MD5        3     ,    C        MD5_CTX   
	 */
	private long[] state = new long[4]; // state (ABCD)
	private long[] count = new long[2]; // number of bits, modulo 2^64 (lsb
										// first)
	private byte[] buffer = new byte[64]; // input buffer
	/*
	 * digestHexStr MD5         ,           16  ASCII  .
	 */
	private String digestHexStr;
	/*
	 * digest,          2      ,  128bit MD5 .
	 */
	private byte[] digest = new byte[16];

	/**
	 * getMD5ofStr  MD5        ,          MD5      
	 *           ,          digestHexStr   .
	 */
	public String getMD5ofStr(String inbuf) {
		md5Init();
		md5Update(inbuf.getBytes(), inbuf.length());
		md5Final();
		digestHexStr = "";
		for (int i = 0; i < 16; i++) {
			digestHexStr += byteHEX(digest[i]);
		}
		return digestHexStr;
	}

	//   MD5          ,JavaBean     public            
	public MD5() {
		md5Init();
		return;
	}

	/* md5Init        ,       ,        */
	private void md5Init() {
		count[0] = 0L;
		count[1] = 0L;
		// /* Load magic initialization constants.
		state[0] = 0x67452301L;
		state[1] = 0xefcdab89L;
		state[2] = 0x98badcfeL;
		state[3] = 0x10325476L;
		return;
	}

	/*
	 * F, G, H ,I  4    MD5  ,    MD5 C   ,     
	 *       ,                 , java ,          private  ,       C  。
	 */
	private long F(long x, long y, long z) {
		return (x & y) | ((~x) & z);
	}

	private long G(long x, long y, long z) {
		return (x & z) | (y & (~z));
	}

	private long H(long x, long y, long z) {
		return x ^ y ^ z;
	}

	private long I(long x, long y, long z) {
		return y ^ (x | (~z));
	}

	/*
	 * Rotation is separate from addition to prevent recomputation.
	 */
	private long FF(long a, long b, long c, long d, long x, long s, long ac) {
		a += F(b, c, d) + x + ac;
		a = ((int) a << s) | ((int) a >>> (32 - s));
		a += b;
		return a;
	}

	private long GG(long a, long b, long c, long d, long x, long s, long ac) {
		a += G(b, c, d) + x + ac;
		a = ((int) a << s) | ((int) a >>> (32 - s));
		a += b;
		return a;
	}

	private long HH(long a, long b, long c, long d, long x, long s, long ac) {
		a += H(b, c, d) + x + ac;
		a = ((int) a << s) | ((int) a >>> (32 - s));
		a += b;
		return a;
	}

	private long II(long a, long b, long c, long d, long x, long s, long ac) {
		a += I(b, c, d) + x + ac;
		a = ((int) a << s) | ((int) a >>> (32 - s));
		a += b;
		return a;
	}

	/*
	 * md5Update MD5      ,inbuf        ,inputlen   ,  
	 *    getMD5ofStr  ,        md5init,       private 
	 */
	private void md5Update(byte[] inbuf, int inputLen) {
		int i, index, partLen;
		byte[] block = new byte[64];
		index = (int) (count[0] >>> 3) & 0x3F;
		// /* Update number of bits */
		if ((count[0] += (inputLen << 3)) < (inputLen << 3))
			count[1]++;
		count[1] += (inputLen >>> 29);
		partLen = 64 - index;
		// Transform as many times as possible.
		if (inputLen >= partLen) {
			md5Memcpy(buffer, inbuf, index, 0, partLen);
			md5Transform(buffer);
			for (i = partLen; i + 63 < inputLen; i += 64) {
				md5Memcpy(block, inbuf, 0, i, 64);
				md5Transform(block);
			}
			index = 0;
		} else
			i = 0;
		// /* Buffer remaining input */
		md5Memcpy(buffer, inbuf, index, i, inputLen - i);
	}

	/*
	 * md5Final         
	 */
	private void md5Final() {
		byte[] bits = new byte[8];
		int index, padLen;
		// /* Save number of bits */
		Encode(bits, count, 8);
		// /* Pad out to 56 mod 64.
		index = (int) (count[0] >>> 3) & 0x3f;
		padLen = (index < 56) ? (56 - index) : (120 - index);
		md5Update(PADDING, padLen);
		// /* Append length (before padding) */
		md5Update(bits, 8);
		// /* Store state in digest */
		Encode(digest, state, 16);
	}

	/*
	 * md5Memcpy        byte        , input inpos   len   
	 *      output outpos    
	 */
	private void md5Memcpy(byte[] output, byte[] input, int outpos, int inpos,
			int len) {
		int i;
		for (i = 0; i < len; i++)
			output[outpos + i] = input[inpos + i];
	}

	/*
	 * md5Transform MD5      , md5Update  ,block        
	 */
	private void md5Transform(byte block[]) {
		long a = state[0], b = state[1], c = state[2], d = state[3];
		long[] x = new long[16];
		Decode(x, block, 64);

		/* Round 1 */
		a = FF(a, b, c, d, x[0], S11, 0xd76aa478L); /* 1 */
		d = FF(d, a, b, c, x[1], S12, 0xe8c7b756L); /* 2 */
		c = FF(c, d, a, b, x[2], S13, 0x242070dbL); /* 3 */
		b = FF(b, c, d, a, x[3], S14, 0xc1bdceeeL); /* 4 */
		a = FF(a, b, c, d, x[4], S11, 0xf57c0fafL); /* 5 */
		d = FF(d, a, b, c, x[5], S12, 0x4787c62aL); /* 6 */
		c = FF(c, d, a, b, x[6], S13, 0xa8304613L); /* 7 */
		b = FF(b, c, d, a, x[7], S14, 0xfd469501L); /* 8 */
		a = FF(a, b, c, d, x[8], S11, 0x698098d8L); /* 9 */
		d = FF(d, a, b, c, x[9], S12, 0x8b44f7afL); /* 10 */
		c = FF(c, d, a, b, x[10], S13, 0xffff5bb1L); /* 11 */
		b = FF(b, c, d, a, x[11], S14, 0x895cd7beL); /* 12 */
		a = FF(a, b, c, d, x[12], S11, 0x6b901122L); /* 13 */
		d = FF(d, a, b, c, x[13], S12, 0xfd987193L); /* 14 */
		c = FF(c, d, a, b, x[14], S13, 0xa679438eL); /* 15 */
		b = FF(b, c, d, a, x[15], S14, 0x49b40821L); /* 16 */
		/* Round 2 */
		a = GG(a, b, c, d, x[1], S21, 0xf61e2562L); /* 17 */
		d = GG(d, a, b, c, x[6], S22, 0xc040b340L); /* 18 */
		c = GG(c, d, a, b, x[11], S23, 0x265e5a51L); /* 19 */
		b = GG(b, c, d, a, x[0], S24, 0xe9b6c7aaL); /* 20 */
		a = GG(a, b, c, d, x[5], S21, 0xd62f105dL); /* 21 */
		d = GG(d, a, b, c, x[10], S22, 0x2441453L); /* 22 */
		c = GG(c, d, a, b, x[15], S23, 0xd8a1e681L); /* 23 */
		b = GG(b, c, d, a, x[4], S24, 0xe7d3fbc8L); /* 24 */
		a = GG(a, b, c, d, x[9], S21, 0x21e1cde6L); /* 25 */
		d = GG(d, a, b, c, x[14], S22, 0xc33707d6L); /* 26 */
		c = GG(c, d, a, b, x[3], S23, 0xf4d50d87L); /* 27 */
		b = GG(b, c, d, a, x[8], S24, 0x455a14edL); /* 28 */
		a = GG(a, b, c, d, x[13], S21, 0xa9e3e905L); /* 29 */
		d = GG(d, a, b, c, x[2], S22, 0xfcefa3f8L); /* 30 */
		c = GG(c, d, a, b, x[7], S23, 0x676f02d9L); /* 31 */
		b = GG(b, c, d, a, x[12], S24, 0x8d2a4c8aL); /* 32 */
		/* Round 3 */
		a = HH(a, b, c, d, x[5], S31, 0xfffa3942L); /* 33 */
		d = HH(d, a, b, c, x[8], S32, 0x8771f681L); /* 34 */
		c = HH(c, d, a, b, x[11], S33, 0x6d9d6122L); /* 35 */
		b = HH(b, c, d, a, x[14], S34, 0xfde5380cL); /* 36 */
		a = HH(a, b, c, d, x[1], S31, 0xa4beea44L); /* 37 */
		d = HH(d, a, b, c, x[4], S32, 0x4bdecfa9L); /* 38 */
		c = HH(c, d, a, b, x[7], S33, 0xf6bb4b60L); /* 39 */
		b = HH(b, c, d, a, x[10], S34, 0xbebfbc70L); /* 40 */
		a = HH(a, b, c, d, x[13], S31, 0x289b7ec6L); /* 41 */
		d = HH(d, a, b, c, x[0], S32, 0xeaa127faL); /* 42 */
		c = HH(c, d, a, b, x[3], S33, 0xd4ef3085L); /* 43 */
		b = HH(b, c, d, a, x[6], S34, 0x4881d05L); /* 44 */
		a = HH(a, b, c, d, x[9], S31, 0xd9d4d039L); /* 45 */
		d = HH(d, a, b, c, x[12], S32, 0xe6db99e5L); /* 46 */
		c = HH(c, d, a, b, x[15], S33, 0x1fa27cf8L); /* 47 */
		b = HH(b, c, d, a, x[2], S34, 0xc4ac5665L); /* 48 */
		/* Round 4 */
		a = II(a, b, c, d, x[0], S41, 0xf4292244L); /* 49 */
		d = II(d, a, b, c, x[7], S42, 0x432aff97L); /* 50 */
		c = II(c, d, a, b, x[14], S43, 0xab9423a7L); /* 51 */
		b = II(b, c, d, a, x[5], S44, 0xfc93a039L); /* 52 */
		a = II(a, b, c, d, x[12], S41, 0x655b59c3L); /* 53 */
		d = II(d, a, b, c, x[3], S42, 0x8f0ccc92L); /* 54 */
		c = II(c, d, a, b, x[10], S43, 0xffeff47dL); /* 55 */
		b = II(b, c, d, a, x[1], S44, 0x85845dd1L); /* 56 */
		a = II(a, b, c, d, x[8], S41, 0x6fa87e4fL); /* 57 */
		d = II(d, a, b, c, x[15], S42, 0xfe2ce6e0L); /* 58 */
		c = II(c, d, a, b, x[6], S43, 0xa3014314L); /* 59 */
		b = II(b, c, d, a, x[13], S44, 0x4e0811a1L); /* 60 */
		a = II(a, b, c, d, x[4], S41, 0xf7537e82L); /* 61 */
		d = II(d, a, b, c, x[11], S42, 0xbd3af235L); /* 62 */
		c = II(c, d, a, b, x[2], S43, 0x2ad7d2bbL); /* 63 */
		b = II(b, c, d, a, x[9], S44, 0xeb86d391L); /* 64 */
		state[0] += a;
		state[1] += b;
		state[2] += c;
		state[3] += d;
	}

	/*
	 * Encode long       byte  ,  java long   64bit ,    32bit,     C     
	 */
	private void Encode(byte[] output, long[] input, int len) {
		int i, j;
		for (i = 0, j = 0; j < len; i++, j += 4) {
			output[j] = (byte) (input[i] & 0xffL);
			output[j + 1] = (byte) ((input[i] >>> 8) & 0xffL);
			output[j + 2] = (byte) ((input[i] >>> 16) & 0xffL);
			output[j + 3] = (byte) ((input[i] >>> 24) & 0xffL);
		}
	}

	/*
	 * Decode byte        long  ,  java long   64bit ,
	 *     32bit, 32bit  ,     C     
	 */
	private void Decode(long[] output, byte[] input, int len) {
		int i, j;
		for (i = 0, j = 0; j < len; i++, j += 4)
			output[i] = b2iu(input[j]) | (b2iu(input[j + 1]) << 8)
					| (b2iu(input[j + 2]) << 16) | (b2iu(input[j + 3]) << 24);
		return;
	}

	/**
	 * b2iu       byte            "  "  ,  java  unsigned  
	 */
	public static long b2iu(byte b) {
		return b < 0 ? b & 0x7F + 128 : b;
	}

	/**
	 * byteHEX(),     byte            ASCII  ,
	 *   java  byte toString       ,     C     sprintf(outbuf,"%02X",ib)
	 */
	public static String byteHEX(byte ib) {
		char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',
				'B', 'C', 'D', 'E', 'F' };
		char[] ob = new char[2];
		ob[0] = Digit[(ib >>> 4) & 0X0F];
		ob[1] = Digit[ib & 0X0F];
		String s = new String(ob);
		return s;
	}
	
	
	//-----------------------------------------------------------

	/**
	 *        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).toUpperCase();
	}
	  
	/**
	 *        SHA1 !
	 * 
	 * @param file
	 * @return
	 */
	public static String getFileSHA1(File file) {
		if (!file.isFile()) {
			return null;
		}
		MessageDigest digest = null;
		FileInputStream in = null;
		byte buffer[] = new byte[1024];
		int len;
		try {
			digest = MessageDigest.getInstance("SHA1");
			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).toUpperCase();
	}
	
	/**
	 *        CRC32 !
	 * @param file
	 * @return
	 * @throws Exception
	 */
	public static String getFileCRC32(File file) {
		FileInputStream fileinputstream;
		try {
			fileinputstream = new FileInputStream(file);
			CRC32 crc32 = new CRC32();
			for (CheckedInputStream checkedinputstream = new CheckedInputStream(
					fileinputstream, crc32); checkedinputstream.read() != -1;) {
			}
			return Long.toHexString(crc32.getValue());
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	
	/**
	 *          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;
	}
	
	/**
	 *          SHA1 
	 * 
	 * @param file
	 * @param listChild
	 *            ;true         
	 * @return
	 */
	public static Map<String, String> getDirSHA1(File file, boolean listChild) {
		if (!file.isDirectory()) {
			return null;
		}
		// <filepath,SHA1>
		Map<String, String> map = new HashMap<String, String>();
		String sha1;
		File files[] = file.listFiles();
		for (int i = 0; i < files.length; i++) {
			File f = files[i];
			if (f.isDirectory() && listChild) {
				map.putAll(getDirSHA1(f, listChild));
			} else {
				sha1 = getFileSHA1(f);
				if (sha1 != null) {
					map.put(f.getPath(), sha1);
				}
			}
		}
		return map;
	}

	/**
	 *          CRC32 
	 * 
	 * @param file
	 * @param listChild
	 *            ;true         
	 * @return
	 */
	public static Map<String, String> getDirCRC32(File file, boolean listChild) {
		if (!file.isDirectory()) {
			return null;
		}
		// <filepath,CRC32>
		Map<String, String> map = new HashMap<String, String>();
		String crc32;
		File files[] = file.listFiles();
		for (int i = 0; i < files.length; i++) {
			File f = files[i];
			if (f.isDirectory() && listChild) {
				map.putAll(getDirCRC32(f, listChild));
			} else {
				crc32 = getFileCRC32(f);
				if (crc32 != null) {
					map.put(f.getPath(), crc32);
				}
			}
		}
		return map;
	}
}

좋은 웹페이지 즐겨찾기