常见开发字符串处理
package com.ccse.core.util;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.StringWriter;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.security.MessageDigest;
import java.sql.Clob;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import org.apache.commons.codec.binary.Base64;
import org.hibernate.lob.SerializableClob;
import com.ccse.core.util.exception.DsmisException;
/**
* 字符转换类
*
* @author admin
*
*/
public class StringUtil {
public static final String numberChar = "0123456789";
/**
* 判断某个字符串是否为数字
*
* @param str
* @return
*/
public static boolean isNumeric(String str) {
for (int i = str.length(); --i >= 0;) {
if (!Character.isDigit(str.charAt(i))) {
return false;
}
}
return true;
}
/**
* 简单的字符串格式化,性能较好。支持不多于10个占位符,从%1开始计算,数目可变。参数类型可以是字符串、Integer、Object,
* 甚至int等基本类型
* 、以及null,但只是简单的调用toString(),较复杂的情况用String.format()。每个参数可以在表达式出现多次。
*
* @param msgWithFormat
* @param autoQuote
* @param args
* @return
*/
public static StringBuilder formatMsg(CharSequence msgWithFormat,
boolean autoQuote, Object... args) {
int argsLen = args.length;
boolean markFound = false;
StringBuilder sb = new StringBuilder(msgWithFormat);
if (argsLen > 0) {
for (int i = 0; i < argsLen; i++) {
String flag = "%" + (i + 1);
int idx = sb.indexOf(flag);
// 支持多次出现、替换的代码
while (idx >= 0) {
markFound = true;
sb.replace(idx, idx + 2, toString(args[i], autoQuote));
idx = sb.indexOf(flag);
}
}
if (args[argsLen - 1] instanceof Throwable) {
StringWriter sw = new StringWriter();
((Throwable) args[argsLen - 1])
.printStackTrace(new PrintWriter(sw));
sb.append("\n").append(sw.toString());
} else if (argsLen == 1 && !markFound) {
sb.append(args[argsLen - 1].toString());
}
}
return sb;
}
public static StringBuilder formatMsg(String msgWithFormat, Object... args) {
return formatMsg(new StringBuilder(msgWithFormat), true, args);
}
public static String toString(Object obj, boolean autoQuote) {
StringBuilder sb = new StringBuilder();
if (obj == null) {
sb.append("NULL");
} else {
if (obj instanceof Object[]) {
for (int i = 0; i < ((Object[]) obj).length; i++) {
sb.append(((Object[]) obj)[i]).append(", ");
}
if (sb.length() > 0) {
sb.delete(sb.length() - 2, sb.length());
}
} else {
sb.append(obj.toString());
}
}
if (autoQuote
&& sb.length() > 0
&& !((sb.charAt(0) == '[' && sb.charAt(sb.length() - 1) == ']') || (sb
.charAt(0) == '{' && sb.charAt(sb.length() - 1) == '}'))) {
sb.insert(0, "[").append("]");
}
return sb.toString();
}
/**
* 把字符串中的带‘与"转成\'与\"
*
* @param orgStr
* @return
*/
public static String convertQuot(String orgStr) {
return orgStr.replace("'", "\\'").replace("\"", "\\\"");
}
public static synchronized String encryptSha256(String inputStr) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte digest[] = md.digest(inputStr.getBytes("UTF-8"));
return new String(Base64.encodeBase64(digest));
// return (new BASE64Encoder()).encode(digest);
// return new String(Hex.encodeHex(digest));
} catch (Exception e) {
return null;
}
}
/**
* HTML实体编码转成普通的编码
*
* @param dataStr
* @return
*/
public static String htmlEntityToString(final String dataStr) {
int start = 0;
int end = 0;
final StringBuffer buffer = new StringBuffer();
while (start > -1) {
int system = 10;// 进制
if (start == 0) {
int t = dataStr.indexOf("&#");
if (start != t)
start = t;
}
end = dataStr.indexOf(";", start + 2);
String charStr = "";
if (end != -1) {
charStr = dataStr.substring(start + 2, end);
// 判断进制
char s = charStr.charAt(0);
if (s == 'x' || s == 'X') {
system = 16;
charStr = charStr.substring(1);
}
}
// 转换
try {
char letter = (char) Integer.parseInt(charStr, system);
buffer.append(new Character(letter).toString());
} catch (NumberFormatException e) {
e.printStackTrace();
}
// 处理当前unicode字符到下一个unicode字符之间的非unicode字符
start = dataStr.indexOf("&#", end);
if (start - end > 1) {
buffer.append(dataStr.substring(end + 1, start));
}
// 处理最后面的非unicode字符
if (start == -1) {
int length = dataStr.length();
if (end + 1 != length) {
buffer.append(dataStr.substring(end + 1, length));
}
}
}
return buffer.toString();
}
/**
* 把String转成html实体字符
*
* @param str
* @return
*/
public static String stringToHtmlEntity(String str) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
switch (c) {
case 0x0A:
sb.append(c);
break;
case '<':
sb.append("<");
break;
case '>':
sb.append(">");
break;
case '&':
sb.append("&");
break;
case '\'':
sb.append("'");
break;
case '"':
sb.append(""");
break;
default:
if ((c < ' ') || (c > 0x7E)) {
sb.append("&#x");
sb.append(Integer.toString(c, 16));
sb.append(';');
} else {
sb.append(c);
}
}
}
return sb.toString();
}
/**
* 替换一个字符串中的某些指定字符
* @param strData String 原始字符串
* @param regex String 要替换的字符串
* @param replacement String 替代字符串
* @return String 替换后的字符串
*/
public static String replaceString(String strData, String regex, String replacement)
{
if (strData == null) {
return null;
}
int index;
index = strData.indexOf(regex);
String strNew = "";
if (index >= 0)
{
while (index >= 0)
{
strNew += strData.substring(0, index) + replacement;
strData = strData.substring(index + regex.length());
index = strData.indexOf(regex);
}
strNew += strData;
return strNew;
}
return strData;
}
/**
* 替换字符串中特殊字符
*/
public static String encodeString(String strData)
{
if (strData == null)
{
return "";
}
strData = replaceString(strData, "&", "&");
strData = replaceString(strData, "<", "<");
strData = replaceString(strData, ">", ">");
strData = replaceString(strData, "'", "'");
strData = replaceString(strData, "\"", """);
return strData;
}
/**
* 还原字符串中特殊字符
*/
public static String decodeString(String strData)
{
strData = replaceString(strData, "<", "<");
strData = replaceString(strData, ">", ">");
strData = replaceString(strData, "'", "'");
strData = replaceString(strData, """, "\"");
strData = replaceString(strData, "&", "&");
return strData;
}
/**
* 把特殊字符转成html实体字符
*
* @param str
* @return
*/
public static String specialStringToHtmlEntity(String str) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
switch (c) {
case 0x0A:
sb.append("");
break;
case '<':
sb.append("<");
break;
case '>':
sb.append(">");
break;
case '&':
sb.append("&");
break;
case '\'':
sb.append("'");
break;
case '"':
sb.append(""");
break;
default:
sb.append(c);
}
}
return sb.toString();
}
/**
* 字符串 转unicode
*
* @param s
* @return
*/
public static String stringToUnicode(String s) {
String unicode = "";
char[] charAry = new char[s.length()];
for (int i = 0; i < charAry.length; i++) {
charAry[i] = (char) s.charAt(i);
unicode += "\\u" + Integer.toString(charAry[i], 16);
}
return unicode;
}
/**
* unicode转字符串
*
* @param unicodeStr
* @return
*/
public static String unicodeToString(String unicodeStr) {
StringBuffer sb = new StringBuffer();
String str[] = unicodeStr.toUpperCase().split("\\\\U");
for (int i = 0; i < str.length; i++) {
if (str[i].equals(""))
continue;
char c = (char) Integer.parseInt(str[i].trim(), 16);
sb.append(c);
}
return sb.toString();
}
public static void main(String[] args) {
String password = "+-!@#$%^*()?/|!~、餐厅、厨房、油漆间、蓄电池室 saaaa AAAA未aaaa>命aaaa'名aaaa&任aaaa<ccc'务";
String result = specialStringToHtmlEntity(password);
System.out.println(result);
// String str="未命名任务";
// String result=htmlEntityToString(str);
// byte[]dis={-10, -32, -95, -30, -84, 65, -108, 90, -102, -89, -1,
// -118, -118, -86, 12, -21, -63, 42, 59, -52, -104, 26, -110, -102,
// -43, -49, -127, 10, 9, 14, 17, -82};
// System.out.println("array:"+ new String(Hex.encodeHex(dis)));
// System.out.println("result:" + result);
// String content="pd6717864949166496642.40.连线2";
// String encode=stringToUnicode(content);
// String vm = "123";
// System.out.println(StringUtil.get8rands());
// System.out.println("another:" + unicodeToString(encode));
//Date d=new Date();
//Timestamp timeStamp=new Timestamp(d.getTime());
//System.out.println(StringUtil.object2String(timeStamp));
}
/**
* 转换html
*
* @param inputString
* @return
*/
public static String html2Text(String inputString) {
String htmlStr = inputString; // 含html标签的字符串
String textStr = "";
java.util.regex.Pattern p_script;
java.util.regex.Matcher m_script;
java.util.regex.Pattern p_style;
java.util.regex.Matcher m_style;
java.util.regex.Pattern p_html;
java.util.regex.Matcher m_html;
try {
String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>"; // 定义script的正则表达式{或<script>]*?>[\s\S]*?<\/script>
// }
String regEx_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>"; // 定义style的正则表达式{或<style>]*?>[\s\S]*?<\/style>
// }
String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式
p_script = java.util.regex.Pattern.compile(regEx_script,
java.util.regex.Pattern.CASE_INSENSITIVE);
m_script = p_script.matcher(htmlStr);
htmlStr = m_script.replaceAll(""); // 过滤script标签
p_style = java.util.regex.Pattern.compile(regEx_style,
java.util.regex.Pattern.CASE_INSENSITIVE);
m_style = p_style.matcher(htmlStr);
htmlStr = m_style.replaceAll(""); // 过滤style标签
p_html = java.util.regex.Pattern.compile(regEx_html,
java.util.regex.Pattern.CASE_INSENSITIVE);
m_html = p_html.matcher(htmlStr);
htmlStr = m_html.replaceAll(""); // 过滤html标签
textStr = htmlStr;
} catch (Exception e) {
System.err.println("Html2Text: " + e.getMessage());
}
return textStr;// 返回文本字符串
}
/**
* 获取8位随机字符串
*
* @return
*/
public static String get8rands() {
Random rd = new Random(); // 創建隨機對象
String n = ""; // 保存隨機數
int rdGet; // 取得隨機數
do {
if (rd.nextInt() % 2 == 1) {
rdGet = Math.abs(rd.nextInt()) % 10 + 48; // 產生48到57的隨機數(0-9的鍵位值)
} else {
rdGet = Math.abs(rd.nextInt()) % 26 + 97; // 產生97到122的隨機數(a-z的鍵位值)
}
char num1 = (char) rdGet; // int轉換char
String dd = Character.toString(num1);
n += dd;
} while (n.length() < 8);// 設定長度,此處假定長度小於8
return n;
}
// 字符串是否空
public static boolean isEmpty(String str) {
return (str == null || str.trim().equals(""));
}
// 字符串是否不空
public static boolean isNotEmpty(String str) {
return (str != null && !str.trim().equals(""));
}
/**
* 将CLOB转成String ,静态方法
*
* @param clob
* 字段
* @return 内容字串,如果出现错误,返回null
*/
public final static String clob2String(Clob clob) {
if (clob == null) {
return null;
}
StringBuffer sb = new StringBuffer(65535);// 64K
Reader clobStream = null;// 创建一个输入流对象
try {
clobStream = clob.getCharacterStream();
char[] b = new char[60000];// 每次获取60K
int i = 0;
while ((i = clobStream.read(b)) != -1) {
sb.append(b, 0, i);
}
} catch (Exception ex) {
sb = null;
} finally {
try {
if (clobStream != null)
clobStream.close();
} catch (Exception e) {
}
}
if (sb == null)
return null;
else
return sb.toString();
}
/**
* 把 11,22,33的字符串转换为'11','22','33'类型的字符串
*
* @param str
* 源字符串
* @return
*/
public static String splitStrToStr(String str) {
if (StringUtil.isNotEmpty(str)) {
String[] arr = str.split(",");
StringBuffer buffer = new StringBuffer("");
int length = arr.length;
for (int i = 0; i < length; i++) {
if (i != length - 1) {
buffer.append("'" + arr[i] + "',");
} else {
buffer.append("'" + arr[i] + "'");
}
}
return buffer.toString();
} else {
return null;
}
}
/**
* 如果一个字符串的值为空,根据msg抛出异常
*
* @param target
* 判断的字符串
* @param msg
* 异常信息
*/
public static void ifEmptyThrowException(String target, String msg) {
if (StringUtil.isEmpty(target)) {
throw new DsmisException(msg);
}
}
/**
* 生成定长的随机数
*
* @param length
* 指定随机数长度
* @return
*/
public static String getRandomString(int length) {
StringBuffer sb = new StringBuffer();
Random random = new Random();
for (int i = 0; i < length; i++) {
sb.append(numberChar.charAt(random.nextInt(numberChar.length())));
}
return sb.toString();
}
/**
* 将List转换成String
*
* @param List
* list
* @return
*/
public static String switchListToString(List<String> list) {
String str = "";
if (list != null && !list.isEmpty()) {
str += "(";
for (Object o : list) {
str += "'" + o + "',";
}
str = str.substring(0, str.length() - 1);
str += ")";
}
return str;
}
/**
* 如果字符串为null,返回一个空字符串
*
* @param str
* @return
*/
public static String null2EmptyStr(String str) {
if(str==null){
return "";
}else{
return str;
}
}
/**
* 设置对象Date属性对应的String属性。若Date类型值为null,则String类型设置为“”
* @param obj
*/
public static List setListObjectDateStrValue(List list){
try {
if(list!=null && !list.isEmpty()){
for (Object obj : list) {
setObjectDateStrValue(obj);
}
}
return list;
} catch (Exception e) {
//e.printStackTrace();
throw new DsmisException("设置对象Date属性对应的String属性时出错");
}
}
/**
* 设置对象Date属性对应的String属性
* Date类型值为null,则String类型设置为“”
* @param obj
*/
public static Object setObjectDateStrValue(Object obj){
try {
//获取实体类的所有属性,返回Field数组
//System.out.println("--------------------"+obj+"--------------------");
Field[] field = obj.getClass().getDeclaredFields();
Method[] methods =obj.getClass().getDeclaredMethods();
//集成以Str结尾的setXXXDateStr方法
List<String> setXXXDateStrList=new ArrayList<String>();
for (int i = 0; i < methods.length; i++) {
String mName=methods[i].getName();
if(mName!=null && !"".equals(mName) && mName.startsWith("set") && mName.lastIndexOf("Str")!=-1){
setXXXDateStrList.add(mName);
}
}
// 遍历所有属性
for (int j = 0; j < field.length; j++) {
// 获取属性的名字
String name = field[j].getName();
//System.out.println("field:="+name);
// 将属性的首字符大写,方便构造get,set方法
name = name.substring(0, 1).toUpperCase() + name.substring(1);
// 获取属性的类型
String type = field[j].getGenericType().toString();
//设置临时制
//String randomValue=String.valueOf(new Random().nextInt(100));
// 设置DateStr的值,Date属性值不设置
if (type.equals("class java.util.Date") && ListUtil.isNotEmpty(setXXXDateStrList)){
Method m = obj.getClass().getMethod("get" + name);
Date value = (Date) m.invoke(obj);
if(setXXXDateStrList.contains("set"+name+"Str")){
if (value == null) {
m = obj.getClass().getMethod("set"+name+"Str",String.class);
m.invoke(obj, "");
}else{
m = obj.getClass().getMethod("set"+name+"Str",String.class);
DateFormat df =new SimpleDateFormat("yyyy-MM-dd");
m.invoke(obj, df.format(value));
}
}
}
else if (type.equals("class java.lang.String")) { // 如果type是类类型,则前面包含"class ",后面跟类名
Method m = obj.getClass().getMethod("get" + name);
String value = (String) m.invoke(obj); // 调用getter方法获取属性值
if (value == null) {
m = obj.getClass().getMethod("set"+name,String.class);
m.invoke(obj, "");
}
}
else if (type.equals("class java.lang.Short")) {
Method m = obj.getClass().getMethod("get" + name);
Short value = (Short) m.invoke(obj); // 调用getter方法获取属性值
if (value == null) {
m = obj.getClass().getMethod("set"+name,Short.class);
m.invoke(obj, Short.parseShort("0"));
}
}
else if (type.equals("class java.lang.Integer")) {
Method m = obj.getClass().getMethod("get" + name);
Integer value = (Integer) m.invoke(obj);
if (value == null) {
m = obj.getClass().getMethod("set"+name,Integer.class);
m.invoke(obj, Integer.valueOf("0"));
}
}
else if (type.equals("class java.lang.Double")) {
Method m = obj.getClass().getMethod("get" + name);
Double value = (Double) m.invoke(obj);
if (value == null) {
m = obj.getClass().getMethod("set"+name,Double.class);
m.invoke(obj, Double.parseDouble("0.00"));
}
}
}
return obj;
} catch (Exception e) {
e.printStackTrace();
throw new DsmisException("设置对象Date属性对应的String属性时出错");
}
}
/**
* 转化double数字为字符串
* @param target 要转换的Double类型的数字
* @param precision 小数点位数,支持1到4位
* @return
*/
public String formatDoubleToStr(Double target, int precision) {
if (target == null) {
return null;
}
if (precision == 1) { //1位小数
DecimalFormat format1 = new DecimalFormat("0.0"); //两位小数
return format1.format(target);
} else if (precision == 2) { //2位小数
DecimalFormat format2 = new DecimalFormat("0.00"); //两位小数
return format2.format(target);
} else if (precision == 3) { //3位小数
DecimalFormat format3 = new DecimalFormat("0.000"); //两位小数
return format3.format(target);
} else if (precision == 4) { //4位小数
DecimalFormat format4 = new DecimalFormat("0.0000"); //两位小数
return format4.format(target);
}
return null;
}
/**
* 转化Object为字符串,若Object值为null,返回空串
* 日期类型格式化格式为yyyy-MM-dd HH:mm:ss
* @param obj
* @return
*/
public static String object2String(Object obj){
DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
if(obj!=null){
if(obj instanceof Date){
String dateStr=format.format(obj);
return dateStr;
}else if(obj instanceof Timestamp){
String dateStr=format.format(obj);
return dateStr;
}else if (obj instanceof SerializableClob) {
SerializableClob b = (SerializableClob) obj;
return StringUtil.clob2String(b);
}else{
return String.valueOf(obj);
}
}else{
return "";
}
}
/**
* map中属性的对象是单一对象,调用该方法
*/
public static String mapToXml(Map<String,String> data){
StringBuffer xmlData = new StringBuffer("");
// String header = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>";
// xmlData.append(header);
// xmlData.append("<data>");
Set<String> keys = data.keySet();
Iterator<String> iter = keys.iterator();
while(iter.hasNext()){
String key = iter.next();
String value = data.get(key);
if(StringUtil.isEmpty(value)){
value = "";
}
if(value.trim().toLowerCase().equals("null")){
value = "";
}
xmlData.append("<" + key + ">" + StringUtil.specialStringToHtmlEntity(value) + "</" + key + ">");
}
// xmlData.append("</data>");
return xmlData.toString();
}
/**
* 若map中属性的对象是list中的一个元素,调用该方法
* @param data
* @param title
* @return
*/
public static String mapToXmlByDataAndTitle(Map<String,String> data, String title){
StringBuffer xmlData = new StringBuffer("");
//String header = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>";
//xmlData.append(header);
xmlData.append("<" + title + ">");
Set<String> keys = data.keySet();
Iterator<String> iter = keys.iterator();
while(iter.hasNext()){
String key = iter.next();
String value = data.get(key);
if(StringUtil.isEmpty(value)){
value = "";
}
if(value.trim().toLowerCase().equals("null")){
value = "";
}
xmlData.append("<" + key + ">" + StringUtil.specialStringToHtmlEntity(value) + "</" + key + ">");
}
xmlData.append("</" + title + ">");
return xmlData.toString();
}
}