天天看點

Java筆記17:JAVA常用函數

**  

 * 根據傳入的格式擷取日期  

 *   

 * @param format  

 *            如:YYYYMMDD || MM/dd/yyyy, hh:mm:ss  

 * @return 字元串的日期  

 */  

public String getSysDate(String format) {   

    String dateStr = "";   

    try {   

        Format formatter;   

        Date date = new Date();   

        formatter = new SimpleDateFormat(format);   

        dateStr = formatter.format(date);   

    } catch (Exception e) {   

        System.out.println(e);   

    }   

    return dateStr;   

}   

/**  

public String getFormatDate(Date date, String format) {   

 * 擷取分割後的字元串數組資訊  

 * @param Str  

 * @param Split  

 * @return 字元串數組  

public String[] getSplit(String Str, String Split) {   

    return Str.split(Split);   

 * 把字元串轉換成指定的日期格式  

 * @param str  

 * @return  

public Date Convert(String str, String format) {   

    java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(format);   

        java.util.Date d = sdf.parse(str);   

        return d;   

    } catch (Exception ex) {   

        ex.printStackTrace();   

        return null;   

 * 擷取月的天數  

 * @param year  

 * @param month  

public static int getdays(String year, String month) {   

    int yearInt = Integer.parseInt(year);   

    int monthInt = Integer.parseInt(month);   

    int monthdays = 31;   

    switch (monthInt) {   

    case 1:   

    case 3:   

    case 5:   

    case 7:   

    case 8:   

    case 10:   

    case 12: {   

        monthdays = 31;   

        break;   

    case 2: {   

        if (isLeapyear(yearInt)) {   

            monthdays = 29;   

        } else {   

            monthdays = 28;   

        }   

    case 4:   

    case 6:   

    case 9:   

    case 11: {   

        monthdays = 30;   

    return monthdays;   

 * 判斷閏年  

public static boolean isLeapyear(int year) {   

    if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {   

        return true;   

    } else {   

        return false;   

 * 判斷某天是星期幾  

 * @param strDate  

 * @return 0 表示是星期天  

public static int getWeekByDate(String strDate) {   

    int dayOfWeek = 0;   

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");   

        Calendar calendar = Calendar.getInstance();   

        date = sdf.parse(strDate);   

        calendar.setTime(date);   

        dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);   

        e.printStackTrace();   

    return dayOfWeek - 1;   

 * 判斷字元串是不是數字  

public static boolean isNumeric(String str) {   

    Pattern pattern = Pattern.compile("[0-9]*");   

    Matcher isNum = pattern.matcher(str);   

    if (!isNum.matches()) {   

    return true;   

 * 獲得距給定日期countday的字元串格式  

 * @param date  

 * @param countday  

 * @param flag  

 *            為true表示日期前,為false表示日期後  

 * @return YYYY-MM-DD  

public String getDateString(Date date, int countday, boolean flag) {   

    String datestr = "";   

    if (flag) {   

        datestr = getFormatDate(new Date((new Date()).getTime() - countday   

                * 24 * 60 * 60 * 1000l), "yyyy-MM-dd");   

        datestr = getFormatDate(new Date((new Date()).getTime() + countday   

    return datestr;   

/***************************************************************************  

 * 根據兩個時間判斷時間差  

 * @throws ParseException   

 **************************************************************************/  

public Long getDateDifference(Date date1,Date date2) throws ParseException {   

//      Date date1 = new SimpleDateFormat("yyyy-mm-dd").parse("2008-3-31");   

//      Date date2 = new SimpleDateFormat("yyyy-mm-dd").parse("2008-3-30");   

    // 日期相減得到相差的日期   

    long day = (date1.getTime() - date2.getTime()) / (24 * 60 * 60 * 1000) > 0 ? (date1   

            .getTime() - date2.getTime())   

            / (24 * 60 * 60 * 1000)   

            : (date2.getTime() - date1.getTime()) / (24 * 60 * 60 * 1000);   

    return day;   

 * 根據兩個時間來判斷時間的內插補點  

 * @param days  

public Long getDateDifference1(Date date1,Date date2) throws ParseException {   

    long day = (date1.getTime() - date2.getTime())/ (24 * 60 * 60 * 1000);   

 * 傳回目前時間的一個時間差時間  

public static String Ds(int days) {   

    SimpleDateFormat form = new SimpleDateFormat("yyyy-MM-dd");   

    Calendar calendar = Calendar.getInstance();   

    int day = calendar.get(Calendar.DAY_OF_YEAR);   

    calendar.set(Calendar.DAY_OF_YEAR, day - days);   

    Date cc = calendar.getTime();   

    return form.format(cc);   

/*************************************************************************  

 * 擷取系統目前時間  

public static Date getSystemDate(){   

    SimpleDateFormat   sf   =   new   SimpleDateFormat("yyyy-MM-dd");      

    Date   date   =   new   Date();                                                                    

        return new SimpleDateFormat("yyyy-mm-dd").parse(sf.format(date));   

    } catch (ParseException e) {   

    return null;   

 /**  

   * 判斷是否為整數  

   *   

   * @param str 傳入的字元串  

   * @return 是整數傳回true,否則傳回false  

   */  

  public static boolean isInteger(String str) {   

    Pattern pattern = Pattern.compile("^[-//+]?[//d]*$");   

    return pattern.matcher(str).matches();   

 }   

   * 判斷是否為浮點數,包括double和float  

   * @return 是浮點數傳回true,否則傳回false  

  public static boolean isDouble(String str) {   

    Pattern pattern = Pattern.compile("^[-//+]?[.//d]*$");   

  }   

   * 判斷輸入的字元串是否符合Email樣式.  

   * @return 是Email樣式傳回true,否則傳回false  

  public static boolean isEmail(String str) {   

    Pattern pattern = Pattern.compile("^//w+([-+.]//w+)*@//w+([-.]//w+)*//.//w+([-.]//w+)*$");   

   * 判斷輸入的字元串是否為純漢字  

   * @param str 傳入的字元竄  

   * @return 如果是純漢字傳回true,否則傳回false  

  public static boolean isChinese(String str) {   

    Pattern pattern = Pattern.compile("[/u0391-/uFFE5]+$");   

   * 是否為空白,包括null和""  

   * @param str  

   * @return  

  public static boolean isBlank(String str) {   

    return str == null || str.trim().length() == 0;   

   * 判斷是否為質數  

   * @param x  

  public static boolean isPrime(int x) {   

    if (x <= 7) {   

      if (x == 2 || x == 3 || x == 5 || x == 7)   

    int c = 7;   

    if (x % 2 == 0)   

      return false;   

    if (x % 3 == 0)   

    if (x % 5 == 0)   

    int end = (int) Math.sqrt(x);   

    while (c <= end) {   

      if (x % c == 0) {   

      }   

      c += 4;   

      c += 2;   

      c += 6;   

     * 人民币轉成大寫  

     *   

     * @param value  

     * @return String  

     */  

    public static String hangeToBig(double value)   

    {   

        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 QJStr  

    public static final String QJToBJChange(String QJStr)   

        char[] chr = QJStr.toCharArray();   

        String str = "";   

        for (int i = 0; i < chr.length; i++)   

            chr[i] = (char) ((int) chr[i] - 65248);   

            str += chr[i];   

        return str;   

     * 去掉字元串中重複的子字元串  

     * @param str  

    private static String removeSameString(String str)   

        Set<String> mLinkedSet = new LinkedHashSet<String>();   

        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().substring(0, sb.toString().length() - 1);   

/**     

     * 根據指定方法的參數去構造一個新的對象的拷貝并将他傳回  

     * @param obj 原始對象  

     * @return 新對象  

     * @throws NoSuchMethodException      

     * @throws InvocationTargetException      

     * @throws IllegalAccessException      

     * @throws InstantiationException      

     * @throws SecurityException      

     * @throws IllegalArgumentException      

    @SuppressWarnings("unchecked")   

    public static Object copy(Object obj) throws IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException,   

                    InvocationTargetException, NoSuchMethodException   

        //獲得對象的類型       

        Class classType = obj.getClass();   

        //通過預設構造方法去建立一個新的對象,getConstructor的視其參數決定調用哪個構造方法       

        Object objectCopy = classType.getConstructor(new Class[]{}).newInstance(new Object[]{});   

        //獲得對象的所有屬性       

        Field[] fields = classType.getDeclaredFields();   

        for(int i = 0; i < fields.length; i++)   

            //擷取數組中對應的屬性       

            Field field = fields[i];   

            String fieldName = field.getName();   

            String stringLetter = fieldName.substring(0, 1).toUpperCase();   

            //獲得相應屬性的getXXX和setXXX方法名稱       

            String getName = "get" + stringLetter + fieldName.substring(1);   

            String setName = "set" + stringLetter + fieldName.substring(1);   

            //擷取相應的方法       

            Method getMethod = classType.getMethod(getName, new Class[]{});   

            Method setMethod = classType.getMethod(setName, new Class[]{field.getType()});   

            //調用源對象的getXXX()方法       

            Object value = getMethod.invoke(obj, new Object[]{});   

            //調用拷貝對象的setXXX()方法       

            setMethod.invoke(objectCopy, new Object[]{value});   

        return objectCopy;   

//過濾特殊字元   

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

//反過濾特殊字元   

    public static String decoding(String src){   

        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;   

// toUtf8String将檔案名轉成GBK後再附到ContentDisposition   

public static String toUtf8String(String s) {   

    StringBuffer sb = new StringBuffer();   

    for (int i = 0; i < s.length(); i++) {   

        char c = s.charAt(i);   

        if (c >= 0 && c <= 255) {   

            sb.append(c);   

            byte[] b;   

            try {   

                b = Character.toString(c).getBytes("utf-8");   

            } catch (Exception ex) {   

                System.out.println(ex);   

                b = new byte[0];   

            for (int j = 0; j < b.length; j++) {   

                int k = b[j];   

                if (k < 0)   

                    k += 256;   

                sb.append("%" + Integer.toHexString(k).toUpperCase());   

    return sb.toString();   

     * 對位元組流進行GBK解碼  

     * @param byteBuffer  

     * @return  

    public static String decode(ByteBuffer byteBuffer) {   

        Charset charset = Charset.forName("ISO-8859-1");   

        CharsetDecoder decoder = charset.newDecoder();   

        try {   

            CharBuffer charBuffer = decoder.decode(byteBuffer);   

            return new String(charBuffer.toString().getBytes("ISO8859_1"),   

                    "GBK").trim();   

        } catch (Exception e) {   

            return null;   

//實作百分比   

public String myPercent(int y, int z) {   

        String baifenbi = "";// 接受百分比的值   

        double baiy = y * 1.0;   

        double baiz = z * 1.0;   

        double fen = baiy / baiz;   

        // NumberFormat nf = NumberFormat.getPercentInstance(); 注釋掉的也是一種方法   

        // nf.setMinimumFractionDigits( 2 ); 保留到小數點後幾位   

        DecimalFormat df1 = new DecimalFormat("##.00%"); // ##.00%   

                                                            // 百分比格式,後面不足2位的用0補齊   

        // baifenbi=nf.format(fen);   

        baifenbi = df1.format(fen);   

        return baifenbi;   

正規表達式用于字元串處理、表單驗證等場合,實用高效。現将一些常用的表達式收集于此,以備不時之需。    

比對中文字元的正規表達式: [/u4e00-/u9fa5]    

評注:比對中文還真是個頭疼的事,有了這個表達式就好辦了    

比對雙位元組字元(包括漢字在内):[^/x00-/xff]    

評注:可以用來計算字元串的長度(一個雙位元組字元長度計2,ASCII字元計1)    

比對空白行的正規表達式:/n/s*/r    

評注:可以用來删除空白行    

比對HTML标記的正規表達式: <(/S*?)[^>]*>.*? <//1>  <.*? />    

評注:網上流傳的版本太糟糕,上面這個也僅僅能比對部分,對于複雜的嵌套标記依舊無能為力    

比對首尾空白字元的正規表達式:^/s* /s*$    

評注:可以用來删除行首行尾的空白字元(包括空格、制表符、換頁符等等),非常有用的表達式    

比對Email位址的正規表達式:/w+([-+.]/w+)*@/w+([-.]/w+)*/./w+([-.]/w+)*    

評注:表單驗證時很實用    

比對網址URL的正規表達式:[a-zA-z]+://[^/s]*    

評注:網上流傳的版本功能很有限,上面這個基本可以滿足需求    

比對帳号是否合法(字母開頭,允許5-16位元組,允許字母數字下劃線):^[a-zA-Z][a-zA-Z0-9_]{4,15}$    

比對國内電話号碼:/d{3}-/d{8} /d{4}-/d{7}    

評注:比對形式如 0511-4405222 或 021-87888822    

比對騰訊QQ号:[1-9][0-9]{4,}    

評注:騰訊QQ号從10000開始    

比對中國郵政編碼:[1-9]/d{5}(?!/d)    

評注:中國郵政編碼為6位數字    

比對***:/d{15} /d{18}    

評注:中國的***為15位或18位    

比對ip位址:/d+/./d+/./d+/./d+    

評注:提取ip位址時有用    

比對特定數字:    

^[1-9]/d*$    //比對正整數    

^-[1-9]/d*$   //比對負整數    

^-?[1-9]/d*$   //比對整數    

^[1-9]/d* 0$  //比對非負整數(正整數 + 0)    

^-[1-9]/d* 0$   //比對非正整數(負整數 + 0)    

^[1-9]/d*/./d* 0/./d*[1-9]/d*$   //比對正浮點數    

^-([1-9]/d*/./d* 0/./d*[1-9]/d*)$  //比對負浮點數    

^-?([1-9]/d*/./d* 0/./d*[1-9]/d* 0?/.0+ 0)$  //比對浮點數    

^[1-9]/d*/./d* 0/./d*[1-9]/d* 0?/.0+ 0$   //比對非負浮點數(正浮點數 + 0)    

^(-([1-9]/d*/./d* 0/./d*[1-9]/d*)) 0?/.0+ 0$  //比對非正浮點數(負浮點數 + 0)    

評注:處理大量資料時有用,具體應用時注意修正    

比對特定字元串:    

^[A-Za-z]+$  //比對由26個英文字母組成的字元串    

^[A-Z]+$  //比對由26個英文字母的大寫組成的字元串    

^[a-z]+$  //比對由26個英文字母的小寫組成的字元串    

^[A-Za-z0-9]+$  //比對由數字和26個英文字母組成的字元串    

^/w+$  //比對由數字、26個英文字母或者下劃線組成的字元串    

評注:最基本也是最常用的一些表達式    

String.split()方法中,有時需要特殊字元,見下:   

* 點的轉義:.  ==> //u002E  

 美元符号的轉義:$  ==> //u0024  

 乘方符号的轉義:^  ==> //u005E  

 左大括号的轉義:{  ==> //u007B  

 左方括号的轉義:[  ==> //u005B  

 左圓括号的轉義:(  ==> //u0028  

 豎線的轉義:| ==> //u007C  

 右圓括号的轉義:) ==> //u0029  

 星号的轉義:*  ==> //u002A  

 加号的轉義:+  ==> //u002B  

 問号的轉義:?  ==> //u003F  

 反斜杠的轉義:/ ==> //u005C  

 豎線:    | ==>//u007C  

* */  本文轉自    風雨蕭條 部落格,原文連結:    http://blog.51cto.com/1095221645/1562755

    如需轉載請自行聯系原作者