
com.app.common.utils.StringUtil Maven / Gradle / Ivy
package com.app.common.utils;
import com.alibaba.fastjson.JSON;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicLong;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 字符串工具类
*
*
*/
public class StringUtil {
public static String parseJson(T obj) {
if (obj == null) {
return null;
}
if (obj instanceof String) {
return (String) obj;
}
return JSON.toJSONString(obj);
}
/**
* 解析出字符串中的表达式
*
* @param exp
* @return
*/
public static Set parse(String exp) {
int length = exp.length();
int start = 0;
int end = 0;
Set expSet = new HashSet();
while (start > -1 && end > -1 && start < length) {
start = exp.indexOf('{', end);
if (start < 0) {
break;
}
end = exp.indexOf('}', start);
if (end < 0) {
break;
}
String clause = exp.substring(start + 1, end);
expSet.add(clause);
start = end;
}
return expSet;
}
public static boolean contain(String srcMsg, String findedMsg, String split) {
if (isNotEmpty(srcMsg)) {
String[] srcValues = srcMsg.split(split);
if (srcValues != null && srcValues.length > 0) {
for (String s : srcValues) {
if (s.equals(findedMsg)) {
return true;
}
}
return false;
} else {
return isEmpty(findedMsg);
}
} else {
return isEmpty(findedMsg);
}
}
public static List rmSameAndNull(List arrys) {
if (arrys != null && arrys.size() > 0) {
ArrayList list = new ArrayList();
for (String a : arrys) {
if (isNotEmpty(a) && !list.contains(a)) {
list.add(a);
}
}
return list;
} else {
return arrys;
}
}
public static String rmSameAndNull(String arrys, String split) {
if (isNotEmpty(arrys)) {
String[] result = rmSameAndNull(arrys.split(split));
if (result != null && result.length > 0) {
StringBuilder strB = new StringBuilder();
strB.append(result[0]);
for (int i = 1; i < result.length; i++) {
strB.append(split).append(result[i]);
}
return strB.toString();
} else {
return "";
}
} else {
return arrys;
}
}
public static String[] rmSameAndNull(String[] arrys) {
if (arrys != null && arrys.length > 0) {
ArrayList list = new ArrayList();
for (String a : arrys) {
if (isNotEmpty(a) && !list.contains(a)) {
list.add(a);
}
}
String[] result = new String[list.size()];
return list.toArray(result);
} else {
return arrys;
}
}
public static String getUnqiueIDLog(long uniqueID) {
return "[" + uniqueID + "]";
}
private static Pattern p = Pattern.compile("\\s*|\t|\r|\n");
public static String replaceBlank(String str) {
String dest = "";
if (str != null) {
Matcher m = p.matcher(str);
dest = m.replaceAll("");
}
return dest;
}
/**
* 判断字符串是否为纯数字
*
* Create Date: 2014年9月29日
*
*
* @param str
* @return true 是,false 否
*/
public static boolean isDigital(String str) {
if (isBlank(str)) {
return false;
}
return str.matches("\\d+");
}
/**
* 判断字符串是否字母加数字
*
* Create Date: 2014年10月9日
*
*
* @param str
* @return true 是,false 否
*/
public static boolean isAlpha(String str) {
if (isBlank(str)) {
return false;
}
return str.matches("^[A-Za-z0-9]+$");
}
/**
* @param str
* 判断字符串是金额格式:####.####
* @return true 是,false 否
*/
public static boolean isMoney(String str) {
try {
new BigDecimal(str);
} catch (Exception e) {
return false;
}
return true;
}
public static boolean isBlank(String str) {
int length;
if ((str == null) || ((length = str.length()) == 0)) {
return true;
}
for (int i = 0; i < length; ++i) {
if (!(Character.isWhitespace(str.charAt(i)))) {
return false;
}
}
return true;
}
public static boolean isNotBlank(String str) {
int length;
if ((str == null) || ((length = str.length()) == 0)) {
return false;
}
for (int i = 0; i < length; ++i) {
if (!(Character.isWhitespace(str.charAt(i)))) {
return true;
}
}
return false;
}
public static void copyValue(Map src, Map des, String key) {
if (!des.containsKey(key) && src.containsKey(key)) {
des.put(key, src.get(key));
}
}
public static void copyValue(Map src, Map des, String[] keys) {
for (String key : keys) {
if (!des.containsKey(key) && src.containsKey(key)) {
des.put(key, src.get(key));
}
}
}
public static boolean isEmpty(String str) {
return ((str == null) || (str.trim().length() == 0));
}
public static boolean isNotEmpty(String str) {
return ((str != null) && (str.trim().length() > 0));
}
public static boolean equalsIgnoreCase(String str1, String str2) {
if (str1 == null) {
return str2 == null;
}
return str1.equalsIgnoreCase(str2);
}
public static boolean equals(String str1, String str2) {
if (str1 == null) {
return str2 == null;
}
return str1.equals(str2);
}
/**
* Convert byte[] to hex string.这里我们可以将byte转换成int,
* 然后利用Integer.toHexString(int)来转换成16进制字符串。
*
* @param src
* byte[] data
* @return hex string
*/
public static String bytesToHexString(byte[] src) {
StringBuilder stringBuilder = new StringBuilder("");
if (src == null || src.length <= 0) {
return null;
}
for (int i = 0; i < src.length; i++) {
int v = src[i] & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
return stringBuilder.toString();
}
/**
* 将byte[]转为字符串
* @param bytes
* @return
*/
public static String byteToString(byte[] bytes) {
if (null == bytes || bytes.length == 0) {
return "";
}
String strContent = "";
try {
strContent = new String(bytes, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return strContent;
}
/**
* Convert hex string to byte[]
*
* @param hexString
* the hex string
* @return byte[]
*/
public static byte[] hexStringToBytes(String hexString) {
if (hexString == null || hexString.equals("")) {
return null;
}
hexString = hexString.toUpperCase();
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] d = new byte[length];
for (int i = 0; i < length; i++) {
int pos = i * 2;
d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
}
return d;
}
/**
* Convert char to byte
*
* @param c
* char
* @return byte
*/
private static byte charToByte(char c) {
return (byte) "0123456789ABCDEF".indexOf(c);
}
private static NumberFormat nf = new DecimalFormat("0.00");
/*
* 金额转换为字符串
*/
public static String toAmountString(float amount) {
return nf.format(amount);
}
public static String toAmountString(BigDecimal amount) {
return nf.format(amount);
}
public static String toAmountString(double amount) {
return nf.format(amount);
}
public static String arrayToString(String[] strs) {
if (strs == null || strs.length < 1) {
return null;
}
int length = strs.length - 1;
StringBuilder strB = new StringBuilder();
for (int i = 0; i <= length; i++) {
strB.append(strs[i]);
if (i != length) {
strB.append(",");
}
}
return strB.toString();
}
public static String[] arrayTrim(String[] strs) {
if (strs == null || strs.length < 1) {
return strs;
}
ArrayList list = new ArrayList();
for (int i = 0; i < strs.length; i++) {
if (!isNull(strs[i])) {
list.add(strs[i]);
}
}
return list.toArray(new String[list.size()]);
}
public static String[] arrayTrimNullAndSame(String[] strs) {
if (strs == null || strs.length < 1) {
return strs;
}
ArrayList list = new ArrayList();
for (int i = 0; i < strs.length; i++) {
if (!isNull(strs[i]) && !list.contains(strs[i])) {
list.add(strs[i]);
}
}
return list.toArray(new String[list.size()]);
}
public static String arrayToString(ArrayList strs) {
if (strs == null || strs.size() < 1) {
return null;
}
int length = strs.size() - 1;
StringBuilder strB = new StringBuilder();
for (int i = 0; i <= length; i++) {
strB.append(strs.get(i));
if (i != length) {
strB.append(",");
}
}
return strB.toString();
}
public static int parseIn(String value, int defaultValue) {
try {
return Integer.parseInt(value);
} catch (Exception e) {
return defaultValue;
}
}
private static String localeIP = null;
public static String getLocaleIP() {
if (localeIP == null) {
try {
InetAddress addr = InetAddress.getLocalHost();
localeIP = addr.getHostAddress().toString();// 获得本机IP
System.out.println("Locale IP:" + localeIP);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return localeIP;
}
private static AtomicLong mdReqID = new AtomicLong();
// public static long getUniqueID() {
// return UniqueID.getAndIncrement();
// }
// public static long getPriceUniqueID() {
// return mdReqID.getAndIncrement();
// }
private static String hostName = null;
public static String getHostName() {
if (hostName == null) {
hostName = getLocalHostName();
}
return hostName;
}
public static String getLocalHostName() {
Object localObject;
try {
localObject = InetAddress.getLocalHost().getHostName();
} catch (Exception localException) {
localObject = "";
}
return (String) localObject;
}
/**
* ISO-8895-1->UTF8
*
* @param str
* @return
*/
public static String charsetConvert(String str) {
return charsetConvert(str, "ISO-8859-1", "UTF-8");
}
/**
*
* @param str
* @param srcEncode
* @param destEncode
* @return
*/
public static String charsetConvert(String str, String srcEncode, String destEncode) {
try {
if (str == null) {
return null;
}
return new String(str.getBytes(srcEncode), destEncode);
} catch (UnsupportedEncodingException e) {
return str;
}
}
public static String getHostAndPort(InetSocketAddress addr) {
return addr.getHostName() + ":" + addr.getPort();
}
/**
*
* @Title: convStr @Description: TODO(转字符串) @author: lq @param: @param
* obj @param: @return @return: String @throws
*/
public static String convStr(Object obj) {
if (obj != null) {
return String.valueOf(obj);
} else {
return null;
}
}
/**
* 对象转map
*
* @Description: objectToMap
* @param obj
* @return
* @author lq.
* @date 2019年11月29日 下午3:36:48
* @version V1.0
*/
public static Map objectToMap(Object obj) {
Map map = new HashMap();
Class> clazz = obj.getClass();
for (Field field : clazz.getDeclaredFields()) {
field.setAccessible(true);
String fieldName = field.getName();
Object value = null;
try {
value = field.get(obj);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
map.put(fieldName, value);
}
return map;
}
/**
* 是否为null
*
* @param str
* @return
*/
public static boolean isNull(String str){
if(str == null){
return true;
}
return false;
}
/**
*
* printStackTraceToString:(获取异常堆栈消息字符串)
* @param @param t
* @param @return 设定文件
* @return String DOM对象
* @throws
* @since CodingExample Ver 1.1
*/
public static String printStackTraceToString(Throwable t) {
StringWriter sw = new StringWriter();
t.printStackTrace(new PrintWriter(sw, true));
return sw.getBuffer().toString();
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy