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 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;
|
}
|
}
|