java经典代码片段

java经典代码片段

写这篇也是用于学习

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("\"", """, replace("<", "<", str));  
    }  
  
    /** 
     * 替换字符串,将被编码的转换成原始码(替换成双引号和小于号) 
     *  
     * @param str 
     *            String 
     * @return String 
     */  
    public static String htmldecode(String str) {  
        if (str == null) {  
            return null;  
        }  
  
        return replace(""", "\"", replace("<", "<", str));  
    }  
  
    private static final String _BR = "
"
; /** * 功能描述:在页面上直接显示文本内容,替换小于号,空格,回车,TAB * * @param str * String 原始字符串 * @return String 替换后的字符串 */ public static String htmlshow(String str) { if (str == null) { return null; } str = replace("<", "<", str); str = replace(" ", " ", str); str = replace("\r\n", _BR, str); str = replace("\n", _BR, str); str = replace("\t", "    ", 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("""); break; case '<': result.append("<"); break; case '>': result.append(">"); break; case '\'': result.append("'"); break; case '&': result.append("&"); 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(""", "\"").replace("'", "\'"); result = result.replace("<", "<").replace(">", ">"); result = result.replace("&", "&"); 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;  
        }  
        //   
        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;  
        }  
        //   
        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;  
        }  
        //   
        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;  
    }  
}  

以上转自:https://wuhaidong.iteye.com/blog/1668689

你可能感兴趣的:(程序,java基础)