MrShi
5 天以前 3a154bdb0a5aaa2c0ac3eac95a6ba747068bd454
keyCabinet-android/lib_coremodel/src/main/java/com/doumee/lib_coremodel/util/StringUtil.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,1133 @@
package com.doumee.lib_coremodel.util;
import android.text.TextUtils;
import org.json.JSONException;
import org.json.JSONObject;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.crypto.Cipher;
import javax.crypto.Mac;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
/**
 * å­—符串操作工具包
 */
public class StringUtil {
    public final static String EMPTY="";
    private final static Pattern emailer = Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
    private final static Pattern identityCard = Pattern.compile("(\\d{14}[0-9xX])|(\\d{17}[0-9xX])");
    private final static Pattern passer = Pattern.compile("[A-Za-z0-9@._-]{6,20}");
    private final static Pattern pureNumber = Pattern.compile("[0-9]{8,30}");
    private final static Pattern phoner = Pattern.compile("1[0-9]{10}");
    private final static Pattern bankCarder = Pattern.compile("[0-9]{16}|[0-9]{19}");
    private final static Pattern user = Pattern.compile("[A-Za-z0-9@._-]{6,20}");
    private final static Pattern Age = Pattern.compile("[0-9]*");
    private final static Pattern Chinese = Pattern.compile("^[\u4e00-\u9fa5]*$");
    private final static Pattern English = Pattern.compile("^[A-Za-z]+$");
    private final static Pattern LinkMan = Pattern.compile("^([A-Za-z]+)$|^([\u4e00-\u9fa5]{2,4})$");
    private final static Pattern LoanAmt = Pattern.compile("\\d{1,10}");
    private final static Pattern LoanExpiry = Pattern.compile("^\\d{1,2}$");
    private final static Pattern BizLicense = Pattern.compile("(?!^[a-zA-Z]+$)[0-9a-zA-Z]+");
    private final static Pattern LoanMoney = Pattern.compile("^(\\d{1,10})(\\.\\d{1,2})?$");
    private final static Pattern HouseSize = Pattern.compile("^(\\d{1,4})(\\.\\d{1,2})?$");
    private final static Pattern ZonuleName = Pattern.compile("[A-Za-z0-9\u4e00-\u9fa5]+");
    private final static Pattern Color = Pattern.compile("[A-Za-z\u4e00-\u9fa5]+");
    private final static Pattern PaiLiang = Pattern.compile("^(\\d{1,2})(\\.\\d{1,2})?$");
    private final static Pattern CarMileage = Pattern.compile("^(\\d{1,8})(\\.\\d{1,2})?$");
    private final static Pattern Money = Pattern.compile("^(\\d{1,8})(\\.\\d{1,2})?$");
    /**
     * åˆ¤æ–­ç»™å®šå­—符串是否空白串。
     * ç©ºç™½ä¸²æ˜¯æŒ‡ç”±ç©ºæ ¼ã€åˆ¶è¡¨ç¬¦ã€å›žè½¦ç¬¦ã€æ¢è¡Œç¬¦ç»„成的字符串
     * è‹¥è¾“入字符串为null或空字符串,返回true
     *
     * @param input
     * @return boolean
     */
    public static boolean isEmpty(String input) {
        if (input == null || "".equals(input)) {
            return true;
        }
        for (int i = 0; i < input.length(); i++) {
            char c = input.charAt(i);
            if (c != ' ' && c != '\t' && c != '\r' && c != '\n') {
                return false;
            }
        }
        return true;
    }
    /**
     * åˆ¤æ–­æ˜¯ä¸æ˜¯ä¸€ä¸ªåˆæ³•的身份证号
     *
     * @param card
     * @return
     */
    public static boolean isIdentityCard(String card) {
        if (card == null || "".equals(card))
            return false;
        return identityCard.matcher(card).matches();
    }
    /**
     * åˆ¤æ–­æ˜¯ä¸æ˜¯ä¸€ä¸ªåˆæ³•的电子邮件地址
     *
     * @param email
     * @return
     */
    public static boolean isEmail(String email) {
        if (TextUtils.isEmpty(email))
            return false;
        return emailer.matcher(email).matches();
    }
    /**
     * åˆ¤æ–­æ˜¯ä¸æ˜¯ä¸€ä¸ªåˆæ³•的用户密码
     *
     * @return
     */
    public static boolean isPassword(String password) {
        if (TextUtils.isEmpty(password))
            return false;
        return passer.matcher(password).matches();
    }
    /**
     * åˆ¤æ–­æ˜¯ä¸æ˜¯ä¸€ä¸ªåˆæ³•的用户名
     *
     * @param custName
     * @return true为合法的用户名
     */
    public static boolean isUser(String custName) {
        if (custName == null || "".equals(custName)) {
            return false;
        }
        return user.matcher(custName).matches();
    }
    public static boolean ispureNumber(String custName) {
        return pureNumber.matcher(custName).matches();
    }
    /**
     * åˆ¤æ–­æ˜¯ä¸æ˜¯ä¸€ä¸ªåˆæ³•的年龄
     *
     * @param age
     * @return
     */
    public static boolean isAge(String age) {
        return Age.matcher(age).matches();
    }
    /**
     * è¿™ä¸ªæ–¹æ³•只支持最大长度为32的随机字符串,如要支持更大长度的,可以适当修改此方法,如前面补、后面补,或者多个uuid相连接
     * @param length
     * @return
     */
    public static String toFixedLengthStringByUUID(int length) {
        //也可以通过UUID来随机生成
        UUID uuid = UUID.randomUUID();
        return uuid.toString().replace("-", "").substring(0, length);
    }
    /**
     * åˆ¤æ–­æ˜¯ä¸æ˜¯ä¸€ä¸ªåˆæ³•的手机号码
     */
    public static boolean isPhone(String phone) {
        if (TextUtils.isEmpty(phone))
            return false;
        return phoner.matcher(phone).matches();
    }
    /**
     * åˆ¤æ–­æ˜¯ä¸æ˜¯ä¸€ä¸ªåˆæ³•的银行卡号
     *
     * @return
     */
    public static boolean isBankCard(String cardNum) {
        if (cardNum == null || "".equals(cardNum))
            return false;
        return bankCarder.matcher(cardNum).matches();
    }
    /**
     * æ•°å­—类型的金额格式化成字符串
     */
    public static String toMoney(Double obj) {
        if (obj == null) {
            return "0.00";
        }
        DecimalFormat df = new DecimalFormat("#,#0.00");
        return df.format(obj);
    }
    /**
     * æ•°å­—格式化,保留两位小数
     *
     * @param obj
     * @return
     */
    public static String douFormat(double obj) {
        DecimalFormat df = new DecimalFormat("0.00");
        return df.format(obj);
    }
    /**
     * èŽ·å–è¾“å…¥çš„å­—ç¬¦é•¿åº¦ï¼Œæ±‰å­—ä¸ºä¸¤ä¸ªå­—ç¬¦
     *
     * @param value
     * @return
     */
    public static int stringLength(String value) {
        int valueLength = 0;
        String chinese = "[\u4e00-\u9fa5]";
        for (int i = 0; i < value.length(); i++) {
            String temp = value.substring(i, i + 1);
            if (temp.matches(chinese)) {
                valueLength += 2;
            } else {
                valueLength += 1;
            }
        }
        return valueLength;
    }
    /**
     * å°†å­—符串转化为double类型
     *
     * @param value
     * @return
     */
    public static double StringToDouble(String value) {
        try {
            if (value == null || "".equals(value))
                return 0.00;
            return Double.parseDouble(value);
        }catch (NumberFormatException e){
            return 0;
        }
    }
    /**
     * å­—符串转整数
     *
     * @param str
     * @return
     */
    public static int StringToInt(String str) {
        try {
            return Integer.parseInt(str);
        } catch (Exception e) {
        }
        return 0;
    }
    /**
     * å­—符串转long
     *
     * @param str
     * @return
     */
    public static long StringToLong(String str) {
        try {
            return Long.parseLong(str);
        } catch (Exception e) {
        }
        return 0;
    }
    /**
     * åˆ¤æ–­å­—符串是否是中文字符
     *
     * @return boolean false å­—符串含有其他非中文字符  true å­—符串都是中文字符串
     */
    public static boolean isChinese(String str) {
        if (null == str || "".equals(str.trim())) {
            return false;
        }
        for (int i = 0; i < str.length(); i++) {
            if (!isChinese(str.charAt(i))) {
                return false;
            }
        }
        return true;
    }
    /**
     * åˆ¤æ–­å­—符是否是中文字符
     *
     * @return boolean false  å­—符不是中文字符  true å­—符是中文字符
     */
    public static boolean isChinese(char c) {
        int v = (int) c;
        return (v >= 19968 && v < 171941);
    }
    /**
     * ä¸­æ–‡æ±‰å­—
     *
     * @param str
     * @return
     */
    public static boolean isC(String str) {
        if (null == str || "".equals(str.trim())) {
            return false;
        }
        return Chinese.matcher(str).matches();
    }
    /**
     * è‹±æ–‡
     *
     * @param str
     * @return
     */
    public static boolean isEnglish(String str) {
        if (null == str || "".equals(str.trim())) {
            return false;
        }
        return English.matcher(str).matches();
    }
    /**
     * é‡‘额
     *
     * @param str
     * @return
     */
    public static boolean isMoney(String str) {
        if (null == str || "".equals(str.trim())) {
            return false;
        }
        return Money.matcher(str).matches();
    }
    /**
     * åˆ¤æ–­åå­—是否含有英文特殊字符(功能应未完善,应该包含中文特殊字符)
     *
     * @return boolean false åå­—不合法,含有英文特殊字符     true åå­—合法 ï¼Œä¸å«æœ‰è‹±æ–‡ç‰¹æ®Šå­—符
     */
    public static boolean isNameLegal(String str) {
        String temp = "@_\\_|_~_`_!_#_$_%_^_&_*_(_)_{_}_[_]_;_:_'_\"_,_<_._>_/_?_-_ï¿¥_!_ @_#_ï¿¥_%_&_*_(_)_——_+_?_~_·_;_:|、_{_}_【_】_1_2_3_4_5_6_7_8_9_0_“_”_…_、_:_《_》_℃_€_£_=_÷_,_。";
        String[] strs = temp.split("_");
        for (int i = 0; i < strs.length; i++) {
            if (str.contains(strs[i])) {
                return false;
            }
        }
        return true;
    }
    /**
     * åˆ¤æ–­æ˜¯å¦ç¬¦åˆè”系人格式
     *
     * @param str
     * @return
     */
    public static boolean isLinkMan(String str) {
        if (null == str || "".equals(str.trim())) {
            return false;
        }
        return LinkMan.matcher(str).matches();
    }
    /**
     * èžèµ„金额
     *
     * @param str
     * @return
     */
    public static boolean isLoanAmt(String str) {
        if (TextUtils.isEmpty(str)) {
            return false;
        }
        return LoanAmt.matcher(str).matches();
    }
    /**
     * è´·æ¬¾æœŸé™
     *
     * @param str
     * @return
     */
    public static boolean isLoanExpiry(String str) {
        if (null == str || "".equals(str.trim())) {
            return false;
        }
        return LoanExpiry.matcher(str).matches();
    }
    /**
     * è¥ä¸šæ‰§ç…§
     *
     * @param str
     * @return
     */
    public static boolean isBizLicense(String str) {
        if (null == str || "".equals(str.trim())) {
            return false;
        }
        return BizLicense.matcher(str).matches();
    }
    /**
     * èµ„金
     *
     * @param str
     * @return
     */
    public static boolean isLoanMoney(String str) {
        if (null == str || "".equals(str.trim())) {
            return false;
        }
        return LoanMoney.matcher(str).matches();
    }
    /**
     * æˆ¿å±‹é¢ç§¯
     *
     * @param str
     * @return
     */
    public static boolean isHouseSize(String str) {
        if (null == str || "".equals(str.trim())) {
            return false;
        }
        return HouseSize.matcher(str).matches();
    }
    public static String cutOffCardNum(String id) {
        if (id.length() == 18) {
            return new StringBuilder().append(id.substring(0, 3)).append("****").append(id.substring(14, 18)).toString();
        } else if (id.length() == 15) {
            return new StringBuilder().append(id.substring(0, 3)).append("****").append(id.substring(11, 15)).toString();
        } else {
            return id;
        }
    }
    public static String cutOffPhone(String phone) {
        if (isPhone(phone)) {
            return new StringBuilder().append(phone.substring(0, 3)).append("****").append(phone.substring(8, 11)).toString();
        } else {
            return phone;
        }
    }
    /**
     * å°åŒºåç§°
     *
     * @param str
     * @return
     */
    public static boolean isZonuleName(String str) {
        if (null == str || "".equals(str.trim())) {
            return false;
        }
        return ZonuleName.matcher(str).matches();
    }
    /**
     * æŽ’量
     *
     * @param str
     * @return
     */
    public static boolean isPaiLiang(String str) {
        if (null == str || "".equals(str.trim())) {
            return false;
        }
        return PaiLiang.matcher(str).matches();
    }
    /**
     * æ±½è½¦é¢œè‰²
     *
     * @param str
     * @return
     */
    public static boolean isColor(String str) {
        if (null == str || "".equals(str.trim())) {
            return false;
        }
        return Color.matcher(str).matches();
    }
    /**
     * æ±½è½¦é‡Œç¨‹
     *
     * @param str
     * @return
     */
    public static boolean isCarMileage(String str) {
        if (null == str || "".equals(str.trim())) {
            return false;
        }
        return CarMileage.matcher(str).matches();
    }
    public static String replaceEach(final String text, final String[] searchList, final String[] replacementList) {
        return replaceEach(text, searchList, replacementList, false, 0);
    }
    public static String dateFormat(String date){
        if(TextUtils.isEmpty(date)){
            return "";
        }
        return date.substring(0,4)+"-"+date.substring(4,6)+"-"+date.substring(6,8)+" "+date.substring(8,10)+":"+date.substring(10,12)+":"+date.substring(12);
    }
    public static String simpleDateFormat(String date){
        if(date==null){
            return "";
        }
        return date.substring(0,4)+"-"+date.substring(4,6)+"-"+date.substring(6,8);
    }
    public static String timeToString(long time){
        SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String d = format.format(new Date(time));
        return d;
    }
    /**
     * <p>
     * Replaces all occurrences of Strings within another String.
     * </p>
     * <p/>
     * <p>
     * A {@code null} reference passed to this method is a no-op, or if
     * any "search string" or "string to replace" is null, that replace will be
     * ignored.
     * </p>
     * <p/>
     * <pre>
     *  StringUtils.replaceEachRepeatedly(null, *, *) = null
     *  StringUtils.replaceEachRepeatedly("", *, *) = ""
     *  StringUtils.replaceEachRepeatedly("aba", null, null) = "aba"
     *  StringUtils.replaceEachRepeatedly("aba", new String[0], null) = "aba"
     *  StringUtils.replaceEachRepeatedly("aba", null, new String[0]) = "aba"
     *  StringUtils.replaceEachRepeatedly("aba", new String[]{"a"}, null) = "aba"
     *  StringUtils.replaceEachRepeatedly("aba", new String[]{"a"}, new String[]{""}) = "b"
     *  StringUtils.replaceEachRepeatedly("aba", new String[]{null}, new String[]{"a"}) = "aba"
     *  StringUtils.replaceEachRepeatedly("abcde", new String[]{"ab", "d"}, new String[]{"w", "t"}) = "wcte"
     *  (example of how it repeats)
     *  StringUtils.replaceEachRepeatedly("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}) = "tcte"
     *  StringUtils.replaceEachRepeatedly("abcde", new String[]{"ab", "d"}, new String[]{"d", "ab"}) = IllegalStateException
     * </pre>
     *
     * @param text            text to search and replace in, no-op if null
     * @param searchList      the Strings to search for, no-op if null
     * @param replacementList the Strings to replace them with, no-op if null
     * @return the text with any replacements processed, {@code null} if
     * null String input
     * @throws IllegalStateException    if the search is repeating and there is an endless loop due
     *                                  to outputs of one being inputs to another
     * @throws IllegalArgumentException if the lengths of the arrays are not the same (null is ok,
     *                                  and/or size 0)
     * @since 2.4
     */
    public static String replaceEach(
            final String text, final String[] searchList, final String[] replacementList, final boolean repeat, final int timeToLive) {
        // mchyzer Performance note: This creates very few new objects (one major goal)
        // let me know if there are performance requests, we can create a harness to measure
        if (text == null || text.isEmpty() || searchList == null ||
                searchList.length == 0 || replacementList == null || replacementList.length == 0) {
            return text;
        }
        // if recursing, this shouldn't be less than 0
        if (timeToLive < 0) {
            throw new IllegalStateException("Aborting to protect against StackOverflowError - " +
                    "output of one loop is the input of another");
        }
        final int searchLength = searchList.length;
        final int replacementLength = replacementList.length;
        // make sure lengths are ok, these need to be equal
        if (searchLength != replacementLength) {
            throw new IllegalArgumentException("Search and Replace array lengths don't match: "
                    + searchLength
                    + " vs "
                    + replacementLength);
        }
        // keep track of which still have matches
        final boolean[] noMoreMatchesForReplIndex = new boolean[searchLength];
        // index on index that the match was found
        int textIndex = -1;
        int replaceIndex = -1;
        int tempIndex = -1;
        // index of replace array that will replace the search string found
        // NOTE: logic duplicated below START
        for (int i = 0; i < searchLength; i++) {
            if (noMoreMatchesForReplIndex[i] || searchList[i] == null ||
                    searchList[i].isEmpty() || replacementList[i] == null) {
                continue;
            }
            tempIndex = text.indexOf(searchList[i]);
            // see if we need to keep searching for this
            if (tempIndex == -1) {
                noMoreMatchesForReplIndex[i] = true;
            } else {
                if (textIndex == -1 || tempIndex < textIndex) {
                    textIndex = tempIndex;
                    replaceIndex = i;
                }
            }
        }
        // NOTE: logic mostly below END
        // no search strings found, we are done
        if (textIndex == -1) {
            return text;
        }
        int start = 0;
        // get a good guess on the size of the result buffer so it doesn't have to double if it goes over a bit
        int increase = 0;
        // count the replacement text elements that are larger than their corresponding text being replaced
        for (int i = 0; i < searchList.length; i++) {
            if (searchList[i] == null || replacementList[i] == null) {
                continue;
            }
            final int greater = replacementList[i].length() - searchList[i].length();
            if (greater > 0) {
                increase += 3 * greater; // assume 3 matches
            }
        }
        // have upper-bound at 20% increase, then let Java take over
        increase = Math.min(increase, text.length() / 5);
        final StringBuilder buf = new StringBuilder(text.length() + increase);
        while (textIndex != -1) {
            for (int i = start; i < textIndex; i++) {
                buf.append(text.charAt(i));
            }
            buf.append(replacementList[replaceIndex]);
            start = textIndex + searchList[replaceIndex].length();
            textIndex = -1;
            replaceIndex = -1;
            tempIndex = -1;
            // find the next earliest match
            // NOTE: logic mostly duplicated above START
            for (int i = 0; i < searchLength; i++) {
                if (noMoreMatchesForReplIndex[i] || searchList[i] == null ||
                        searchList[i].isEmpty() || replacementList[i] == null) {
                    continue;
                }
                tempIndex = text.indexOf(searchList[i], start);
                // see if we need to keep searching for this
                if (tempIndex == -1) {
                    noMoreMatchesForReplIndex[i] = true;
                } else {
                    if (textIndex == -1 || tempIndex < textIndex) {
                        textIndex = tempIndex;
                        replaceIndex = i;
                    }
                }
            }
            // NOTE: logic duplicated above END
        }
        final int textLength = text.length();
        for (int i = start; i < textLength; i++) {
            buf.append(text.charAt(i));
        }
        final String result = buf.toString();
        if (!repeat) {
            return result;
        }
        return replaceEach(result, searchList, replacementList, repeat, timeToLive - 1);
    }
    /**
     * åŠè§’转全角 * @param
     input String. * @return
     å…¨è§’字符串. */
    public static String toSBC(String input) {
        char c[] = input.toCharArray();
        for (int i = 0; i < c.length; i++) {
            if(c[i] == ' ') {
                c[i] = '\u3000';
            }else if(c[i] < '\177') {
                c[i] = (char) (c[i] + 65248);
            }
        }
        return new String(c);
    }
    public static String hashToStr(HashMap<String, Object> map){
        JSONObject clientKey = new JSONObject();
        //  å°†map中的key-value关系存入到set集合中,再使用Map.Entry
        Set entrySet = map.entrySet(); // key-value的set集合
        Iterator it2 = entrySet.iterator();
        while(it2.hasNext()){
            Map.Entry me = (Map.Entry) it2.next();
            Object k = me.getKey();
            Object v = me.getValue();
            try {
                clientKey.put((String)k,v);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return String.valueOf(clientKey);
    }
    /**
     * ç§’转为分钟小时
     * @return
     *//*
    public static String sToMH(int s) {
        int h=0;
        int m=0;
        StringBuilder builder=new StringBuilder();
        if(s/3600>0){
            h=s/3600;
            builder.append(h+MApplication.mContext.getResources().getString(R.string.time_h));
            s-=3600*h;
        }
        if(s/60>0){
            m=s/60;
            builder.append(m+MApplication.mContext.getResources().getString(R.string.time_m));
            s-=m*60;
        }else {
            if(h!=0){
                builder.append(0+MApplication.mContext.getResources().getString(R.string.time_m));
            }
        }
        builder.append(s+ MApplication.mContext.getResources().getString(R.string.time_s));
        return builder.toString();
    }*/
    /**
     * å½±è—æ‰‹æœºä¸­é—´4位
     * @return
     */
    public static String phoneToHind(String s) {
        if(s==null){
            return "";
        }
        if(s.length()==11){
            s=s.substring(0,3)+"****"+s.substring(7);
        }
        return s;
    }
    /**
     * å½±è—é“¶è¡Œå¡å·ç ï¼Œä¿ç•™åŽ4位
     * @return
     */
    public static String bankNumToHind(String s) {
        if(s==null){
            return "";
        }
        if(s.length()>4){
            int size=s.length();
            String s1=s.substring(size-4);
            StringBuffer buffer=new StringBuffer();
            for(int i=0;i<size-4;i++){
                buffer.append("*");
            }
            s=buffer.toString()+s1;
        }
        return s;
    }
    /**
     * SHA加密
     * @return åŠ å¯†ä¹‹åŽçš„å¯†æ–‡
     */
    public static String shaEncrypt(String data) {
        byte[] datas=data.getBytes();
        String result = null;
        try {
            //根据给定的字节数组构造一个密钥,第二参数指定一个密钥算法的名称
            SecretKeySpec signinKey = new SecretKeySpec("Gu5t9xGARNpq86cd98joQYCN3Cozk1qA".getBytes(), "HmacSHA1");
            //生成一个指定 Mac ç®—法 çš„ Mac å¯¹è±¡
            Mac mac = Mac.getInstance("HmacSHA1");
            //用给定密钥初始化 Mac å¯¹è±¡
            mac.init(signinKey);
            //完成 Mac æ“ä½œ
            byte[] rawHmac = mac.doFinal(datas);
            result = new String();
        } catch (NoSuchAlgorithmException e) {
            System.err.println(e.getMessage());
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
        if (null != result) {
            return result;
        } else {
            return null;
        }
    }
    /**
     * byte数组转换为16进制字符串
     *
     * @param bts
     *            æ•°æ®æº
     * @return 16进制字符串
     */
    public static String bytes2Hex(byte[] bts) {
        String des = "";
        String tmp = null;
        for (int i = 0; i < bts.length; i++) {
            tmp = (Integer.toHexString(bts[i] & 0xFF));
            if (tmp.length() == 1) {
                des += "0";
            }
            des += tmp;
        }
        return des;
    }
    // åР坆
    public static String encrypt(String sSrc){
        String sKey = "abcdef0123456789";
        String ivParameter = "0123456789abcdef";
        String result = "";
        try {
            Cipher cipher;
            cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            byte[] raw = sKey.getBytes();
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());// ä½¿ç”¨CBC模式,需要一个向量iv,可增加加密算法的强度
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
            byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
            result = new String();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // æ­¤å¤„使用BASE64做转码。
        return result;
    }
    // è§£å¯†
    public static String decrypt(String sSrc){
        if(sSrc==null){
            return "";
        }
        String sKey = "abcdef0123456789";
        String ivParameter = "0123456789abcdef";
        try {
            byte[] raw = sKey.getBytes("ASCII");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            byte[] encrypted1 = "".getBytes();// å…ˆç”¨base64解密
            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original, "utf-8");
            raw=null;
            encrypted1=null;
            original=null;
            return "{\"data\":"+originalString+"}";
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }
    // è§£å¯†
    public static String decryptNew(String sSrc){
        if(sSrc==null){
            return "";
        }
        String sKey = "abcdef0123456789";
        String ivParameter = "0123456789abcdef";
        try {
            byte[] raw = sKey.getBytes("ASCII");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            byte[] encrypted1 = "".getBytes();// å…ˆç”¨base64解密
            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original, "utf-8");
            raw=null;
            encrypted1=null;
            original=null;
            return originalString;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }
    // è§£å¯†
    public static String decryptNoData(String sSrc){
        if(sSrc==null){
            return "";
        }
        String sKey = "abcdef0123456789";
        String ivParameter = "0123456789abcdef";
        try {
            byte[] raw = sKey.getBytes("ASCII");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            byte[] encrypted1 = "".getBytes();// å…ˆç”¨base64解密
            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original, "utf-8");
            raw=null;
            encrypted1=null;
            original=null;
            return originalString+"}";
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }
    /**
     *
     * @param str
     * @return
     * @throws NumberFormatException
     */
    public static String inputPriceFormatter(String str)throws NumberFormatException {
        String handledStr = null;
        //小数形式的输入
        if(isValid(str).contains(".")){
            float f_price = Float.valueOf(isValid(str));
            handledStr = Float.toString(f_price);
            //整数形式的输入
        }else{
            int i_price = Integer.valueOf(isValid(str));
            handledStr = Integer.toString(i_price);
        }
        return isValid(handledStr);
    }
    /**
     * åˆ¤æ–­æ˜¯å¦ä¸ºç©ºå’Œç©ºä¸²,以NumberFormatException的方式集中处理
     * @param str
     * @return
     * @throws NumberFormatException
     */
    public static String isValid(String str) throws NumberFormatException {
        if(str == null || "".equals(str))
            throw new NumberFormatException();
        return str;
    }
    // get rand color
    public static String getRandColorCode() {
        String r,g,b;
        Random random = new Random();
        r = Integer.toHexString(random.nextInt(256)).toUpperCase();
        g = Integer.toHexString(random.nextInt(256)).toUpperCase();
        b = Integer.toHexString(random.nextInt(256)).toUpperCase();
        r = r.length() == 1 ? "0" + r : r ;
        g = g.length() == 1 ? "0" + g : g ;
        b = b.length() == 1 ? "0" + b : b ;
        return "0xFF"+r + g + b;
    }
    public static boolean isCEN(String txt) {
        Pattern p = Pattern.compile("[0-9]*");
        Matcher m = p.matcher(txt);
        if (m.matches()) {
            return true;
        }
        p = Pattern.compile("[a-zA-Z]");
        m = p.matcher(txt);
        if (m.matches()) {
            return true;
        }
        p = Pattern.compile("[\u4e00-\u9fa5]");
        m = p.matcher(txt);
        if (m.matches()) {
            return true;
        }
        return false;
    }
    public static boolean isLetterOrNum(String txt) {
        Pattern p = Pattern.compile("[0-9]*");
        Matcher m = p.matcher(txt);
        if (m.matches()) {
            return true;
        }
        p = Pattern.compile("[a-zA-Z]");
        m = p.matcher(txt);
        if (m.matches()) {
            return true;
        }
        m = p.matcher(txt);
        if (m.matches()) {
            return true;
        }
        return false;
    }
    public static boolean isNumber(String txt) {
        Pattern p = Pattern.compile("[0-9]*");
        Matcher m = p.matcher(txt);
        if (m.matches()) {
            return true;
        }
        return false;
    }
    /**
     * æ—¥æœŸè½¬æ¢æˆJava字符串
     * @param date
     * @return str
     */
    public static String DateToStr(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String str = format.format(date);
        return str;
    }
    public static String DateToStrSS(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
        String str = format.format(date);
        return str;
    }
    public static String getHM() {
        SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
        String str = format.format(new Date());
        return str;
    }
    public static String DateToStrYMD(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String str = format.format(date);
        return str;
    }
    /**
     * å­—符串转换成日期
     * @param str
     * @return date
     */
    public static Date StrToDate(String str) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            date = format.parse(str);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }
    public static String removeWhiteSpace(String inputStr) {
        String outputStr = "";
        if (inputStr != null && !inputStr.isEmpty()) {
            //移除所有换行和空格
            outputStr = inputStr.replaceAll("\\s+", "");
        }
        return outputStr;
    }
}