字符串工具类




import org.apache.commons.lang.StringUtils;

import javax.crypto.*;
import javax.crypto.spec.DESKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import java.text.DecimalFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class StringUtil {
/**
* 判断字符串是否超长
*
* @param s
* @return true表示超长,false为否
*/
public static boolean isOverLength(String s) {
if (s == null || s.trim().length() <= GlobalConstant.TD_MAX_LENGTH)
return Boolean.FALSE;
return Boolean.TRUE;
}

/**
* 获得超长字符串的省写格式
*
* @param s 超长的字符串
* @return 省写格式
*/
public static String getElideString(String s) {
return s.trim().substring(0, GlobalConstant.TD_MAX_LENGTH - 2).concat(GlobalConstant.SUSPENSION_POINTS);
}

/**
* List类型对象转换成String型,多个元素以,相隔
*
* @param list
* @return String型
*/
public static String formatListToString(List list) {
if (list == null)
return null;
if (list.size() == 0)
return GlobalConstant.STR_EMPTY;
StringBuffer buffer = new StringBuffer();
for (Object obj : list)
buffer.append(GlobalConstant.COMMA).append(obj == null ? GlobalConstant.STR_EMPTY : obj.toString().trim());
if (buffer.length() > 0)
buffer.deleteCharAt(0);
return buffer.toString();
}

/**
* String型对象转换List类型,中间以regex相隔
*
* @param s
* @param regex 分隔符号,默认为,
* @return List类型
*/
public static List<String> formatStringToList(String s, String regex) {
List<String> rstList = new ArrayList<String>();
if (isStrEmpty(regex))
regex = GlobalConstant.COMMA;
if (isStrEmpty(s))
return rstList;
String[] array = s.split(regex);
for (String str : array)
rstList.add(str);
return rstList;
}

/**
* String型对象转换List类型,中间以,相隔
*
* @param s
* @return List类型
*/
public static List<String> formatStringToListByComma(String s) {
List<String> rstList = new ArrayList<String>();
getListElementByString(rstList, s);
return rstList;
}

private static void getListElementByString(List list, String s) {
if (isStrEmpty(s))
list.add(GlobalConstant.STR_EMPTY);
else if (s.indexOf(GlobalConstant.COMMA) == -1) {
list.add(s);
} else {
String temp = s.substring(0, s.indexOf(GlobalConstant.COMMA));
list.add(isStrEmpty(temp) ? GlobalConstant.STR_EMPTY : temp);
getListElementByString(list, s.substring(s.indexOf(GlobalConstant.COMMA) + 1));
}
}

/**
* 方法名称:从字符串中剪切掉某字符后剩余字符
* 方法编号:200001
*
* @param str1 --源字符串
* str2 --需剪切字符串
* @return --剪切掉某字符后剩余字符
*/
public static String getTrimedStringBySpilth(String str1, String str2) {
StringBuffer rst = new StringBuffer();
List l = stringToArrayList(str1, GlobalConstant.COMMA);
while (l.contains(str2)) {
l.remove(str2);
}
int v = l.size();
for (int i = 0; i < v; i++) {
rst.append(l.get(i)).append(GlobalConstant.COMMA);
}
return getTrimedStringByComma(rst.toString()).toString();
}

/**
* 方法名称:从字符串中剪切掉某字符后剩余字符
* 方法编号:200001-1
*
* @param str1 --源字符串
* str2 --需剪切字符串
* @return --剪切掉某字符后剩余字符
*/
public static StringBuffer getTrimedStringBufferBySpilth(StringBuffer str1, String str2) {
return new StringBuffer(getTrimedStringBySpilth(str1.toString(), str2));
}

/**
* 方法名称:从字符串中剪切掉连续重复某字符后的剩余字符
* 方法编号:200002
*
* @param str1 --源字符串
* str2 --重复字符串
* str --剪切结果
* @return --剪切掉某字符后剩余字符
*/

public static String getTrimedStringByRepeatedStr(String str1, String str2, StringBuffer str) {
String rst = GlobalConstant.STR_EMPTY;
if (str1 != null && str2 != null) {
int l = str2.length();
int k = str1.length();
int m = str1.indexOf(str2);
String str3 = new String();
if (k > m + 2 * l)
str3 = str1.substring(m + l, m + 2 * l);
if (m > 0) {
if (str3.equals(str2)) {
str.append(str1.substring(0, m + l));
str1 = str1.substring(m + l, k);
} else {
str.append(str1.substring(0, m + l)).append(str3);
if (m + l + 1 <= k)
str1 = str1.substring(m + l, k);
else
str1 = GlobalConstant.STR_EMPTY;
}
return getTrimedStringByRepeatedStr(str1, str2, str);
} else if (m == 0) {
if (str3.equals(str2)) {
str1 = str1.substring(m + l, k);
if (str.length() == 0) {
str.append(str2);
} else if (!(str.lastIndexOf(str2) == str.length() - l))
str.append(str2);
} else if (str.lastIndexOf(str2) == str.length() - l) {
str1 = str1.substring(m + l, k);
} else {
str.append(str2).append(str3);
str1 = str1.substring(m + l, k);
}
return getTrimedStringByRepeatedStr(str1, str2, str);
}
str.append(str1);
}
if (str != null)
rst = str.toString();
return rst;
}

/**
* 方法名称:去除字符前后,号
* 方法编号:200003
*
* @param str1 --源字符串
* @return --去除字符前后,号的字符
*/
public static StringBuffer getTrimedStringByComma(String str1) {
StringBuffer rst = new StringBuffer();
if (str1 != null) {
int j = str1.indexOf(GlobalConstant.COMMA);
if (j == 0)
str1 = str1.substring(1, str1.length());
j = str1.lastIndexOf(GlobalConstant.COMMA);
if (j == str1.length() - 1 && str1.length() - 1 >= 0)
str1 = str1.substring(0, str1.length() - 1);
rst.append(str1);
}
return rst;
}

/**
* 方法名称:比较2个字符的差异
* 方法编号:200005
*
* @param str1 --字符1
* Str2 --字符2
* @return --0-字符2比字符1少的字符
* 1-字符2比字符1多的字符
*/
public static List compareList(String str1, String str2) {
List rst = new ArrayList();
if (str1 != null && (str1.equals(GlobalConstant.STR_NULL) || str1.equals(GlobalConstant.STR_EMPTY)))
str1 = null;
if (str2 != null && (str2.equals(GlobalConstant.STR_NULL) || str2.equals(GlobalConstant.STR_EMPTY)))
str2 = null;
if (str1 == null) {
rst.add(null);
rst.add(str2);
} else if (str2 == null) {
rst.add(str1);
rst.add(null);
} else {
StringBuffer rst0 = new StringBuffer();
StringBuffer rst1 = new StringBuffer();
List lst1 = stringToArrayList(str1, GlobalConstant.COMMA);
List lst2 = stringToArrayList(str2, GlobalConstant.COMMA);
int j = lst1.size();
for (int i = 0; i < j; i++) {
String s = ((String) lst1.get(i)).trim();
if (!lst2.contains(s)) {
rst0.append(s).append(GlobalConstant.COMMA);
}
}
j = lst2.size();
for (int i = 0; i < j; i++) {
String s = ((String) lst2.get(i)).trim();
if (!lst1.contains(s)) {
rst1.append(s).append(GlobalConstant.COMMA);
}
}
rst0 = getTrimedStringByComma(rst0.toString());
rst1 = getTrimedStringByComma(rst1.toString());
if (rst0.length() == 0)
rst.add(null);
else
rst.add(rst0.toString());

if (rst1.length() == 0)
rst.add(null);
else
rst.add(rst1.toString());
}
return rst;
}

/**
* 通过文件名判断是unix或linux系统
*
* @param fileName 文件名
* @return
* @author kevin
* @date 2005-6-30
*/
public static boolean isUnixOS(String fileName) {
// unix系统的文件名的第一个字符是"/";
if (!isStrEmpty(fileName)) {
String separator = fileName.substring(0, 1);
if ("/".equals(separator))
return true;
else
return false;
} else
return false;
}

public static String getRandomLengthNum(int length) {
StringBuffer str = new StringBuffer();
Random random = new Random();
for (int i = 0; i < length; i++) {
str.append(Math.abs(random.nextInt(10)));
}
return str.toString();
}

/**
* 判断str是否为空
*
* @param str String
* @return boolean true:空;false:非空
* @author:kevin
* @date:2004-12-22
*/
public static boolean isStrEmpty(String str) {
return StringUtils.isEmpty(str);
//return ((str == null) || (str.trim().equals(GlobalConstant.STR_EMPTY)));
}

public static boolean isStrTrimEmpty(String str) {
return (str == null) || (str.trim().equals(GlobalConstant.STR_EMPTY));
}

/**
* 把字符串按格式转化为List
* author: ray
*
* @param str
* @param delim
* @return
*/
public static List stringToArrayList(String str, String delim) {
List list = new ArrayList();
if (!isStrEmpty(str) && delim != null) {
if (str.endsWith(delim)) {
str = str.substring(0, str.length() - 1);
}
int index = str.indexOf(delim);
if (index == -1) {
list.add(str);
return list;
}
while (index != -1) {
String temp = str.substring(0, index);
if (temp != null) {
if (temp.equals(delim)) {
list.add(null);
index = index - delim.length();
} else
list.add(temp);
str = str.substring(index + 1);
index = str.indexOf(delim);
} else
index++;
}
list.add(str.trim());
}
return list;
}

/**
* @param input :
* 输入的中文字符串,需要经过转换
* @return 返回经过字符集转换的字符串
*/
public static String parseChinese(String input)
throws UnsupportedEncodingException {
if (input == null || input.equals(GlobalConstant.STR_EMPTY))
return (GlobalConstant.STR_EMPTY);
byte[] temp = null;
try {
temp = input.getBytes(GlobalConstant.ENG_CODE_PAGE);
} catch (UnsupportedEncodingException e) {
throw new UnsupportedEncodingException(e.getMessage());
}
if (temp == null) {
return (GlobalConstant.STR_EMPTY);
} else {
return (new String(temp, GlobalConstant.CN_CODE_PAGE));
}
}

/**
* 把String按分隔符号转换成String[]
*
* @param str
* @param delim
* @return
*/
public static String[] stringToStringArray(String str, String delim) {
List list = stringToArrayList(str, delim);
Object[] objectStr = list.toArray();
int len = objectStr.length;
String[] strAarray = new String[len];
System.arraycopy(objectStr, 0, strAarray, 0, len);
return strAarray;
}

/**
* 比较2个字符的差异,并将差异部分分别返回
*
* @param oStr
* @param nStr
* @return rst0--String-- oStr差异部分
* rst1--String-- nStr差异部分
*/
public static List compareString(String oStr, String nStr) {
List rst = new ArrayList();
StringBuffer rst0 = new StringBuffer();
StringBuffer rst1 = new StringBuffer();
if (oStr != null && nStr != null) {
List ol = stringToArrayList(oStr, GlobalConstant.COMMA);
List nl = stringToArrayList(nStr, GlobalConstant.COMMA);
int ov = ol.size();
int nv = nl.size();
//去除空格
if (oStr.indexOf(" ") >= 0) {
for (int i = 0; i < ov; i++) {
String s = (String) ol.get(i);
s = s.trim();
ol.set(i, s);
}
}
//去除空格
if (nStr.indexOf(" ") >= 0) {
for (int i = 0; i < nv; i++) {
String s = (String) nl.get(i);
s = s.trim();
nl.set(i, s);
}
}
for (int i = 0; i < ol.size(); i++) {
String s = (String) ol.get(i);
if (nl.contains(s)) {
nl.remove(s);
ol.remove(s);
i--;
} else
rst0.append(s).append(GlobalConstant.COMMA);
}
for (int i = 0; i < nl.size(); i++) {
String s = (String) nl.get(i);
rst1.append(s).append(GlobalConstant.COMMA);
}
rst0 = getTrimedStringByComma(rst0.toString());
rst1 = getTrimedStringByComma(rst1.toString());
}
rst.add(rst0.toString());
rst.add(rst1.toString());
return rst;
}

public static String getDcolumnString(List fieldList) {
StringBuffer rst = new StringBuffer();
int fv = fieldList.size();
for (int i = 0; i < fv; i++) {
String field = (String) fieldList.get(i);
rst.append(field + " AS F" + i);
if (i < fv - 1)
rst.append(GlobalConstant.COMMA);
}
return rst.toString();
}

public static String getRandomNumAndChar(int length) {
String rst = GlobalConstant.STR_EMPTY;
Random random = new Random();
String str1 = "0123456789";//包含数字的字符串
String str2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";//包含字母的字符串
int start1 = random.nextInt(str1.length());//取str1长度范围内的随机值
int start2 = random.nextInt(str2.length());
String c1 = str1.substring(start1, start1 + 1);//截取字符串的一个随机字符
String c2 = str2.substring(start2, start2 + 1);

//再用个循环拼接下,length(密码长度)从全局参数中取
for (int i = 0; i < length; i++) {
start1 = random.nextInt(str1.length());
start2 = random.nextInt(str2.length());
c1 = str1.substring(start1, start1 + 1);
c2 = str2.substring(start2, start2 + 1);
rst += c1;
if (rst.length() >= length)
break;
rst += c2;
if (rst.length() >= length)
break;
}
return rst;
}

/**
* 获取修改后的字符
*
* @return
*/
public static String getEditedStr(String s) {
StringBuffer rst = new StringBuffer();
List l = stringToArrayList(s, GlobalConstant.COMMA);
int v = l.size();
String temp = null;
for (int i = 0; i < v; i++) {
temp = (String) l.get(i);
if (temp.indexOf(GlobalConstant.STR_NULL) < 0 && !temp.endsWith("=") && temp.indexOf("=未知") <= 0)
rst.append(temp).append(GlobalConstant.COMMA);
}
rst = getTrimedStringByComma(rst.toString());
return rst.toString();
}

public static Map stringToMap(String s, String s1, String s2) {
List prsList = stringToArrayList(s, s1);
Map map = null;
int v = prsList.size();
if (v > 0) {
map = new HashMap();
String t = null;
int index = 0;
for (int i = 0; i < v; i++) {
t = (String) prsList.get(i);
index = t.indexOf(s2);
map.put(t.substring(0, index), t.substring(index + 1, t.length()));
}
}
return map;
}

/**
* String[]转换成String
*
* @param array String数组
* @return null或字符串(多个元素以, 相隔)
*/
public static String formateStringArrayToString(String[] array) {
if (array == null)
return null;
if (array.length == 0)
return null;
StringBuffer sb = new StringBuffer();
for (int i = 0; i < array.length; i++) {
sb.append("," + array[i]);
}
return sb.substring(1);
}

/**
* 得到Object的String值
*
* @param obj
* @return String值
*/
public static String valueOf(Object obj) {
return obj == null ? "" : String.valueOf(obj);
}

/**
* 判断String数组是否包含指定String
*
* @param array 指定的String数组
* @param s 指定的String
* @return 包含则返回True,反之则返回false
*/
public static boolean hasContain(String[] array, String s) {
if (isStrEmpty(s))
return Boolean.FALSE;
if (array == null || array.length == 0)
return Boolean.FALSE;
for (String e : array) {
if (s.equals(e))
return Boolean.TRUE;
}
return Boolean.FALSE;
}

/**
* 解析高级查询组件的条件字符串,得到List
*
* @param aqConditions 高级查询组件的条件字符传,格式为:大类ID#小类ID#操作符号ID#值#值类型&...&大类ID#小类ID#操作符号ID#值#值类型
* @return 元素为String[5]的List (String[0]-maxClass, String[1]-minClass, String[2]-option, String[3]-value, String[4]-valueType)
*/
public static List parseAdvancedQueryConditon(String aqConditions) {
List sqlCondtionList = new ArrayList();
if (isStrEmpty(aqConditions))
return sqlCondtionList;
String[] conditionArray = aqConditions.split(GlobalConstant.AND);//条件数组,一个元素表示一个条件
String[] columnArray = null;
int i = 0;
for (i = 0; i < conditionArray.length; i++) {
columnArray = conditionArray[i].split(GlobalConstant.WELL);
if (columnArray.length != 5)
continue;
sqlCondtionList.add(columnArray);
}
conditionArray = null;
columnArray = null;
i = 0;
return sqlCondtionList;
}

/**
* 格式化高级查询组件的条件字符串
*
* @param array String[0]-maxClass, String[1]-minClass, String[2]-option, String[3]-value, String[4]-valueType
* @return
*/
public static void formatAdvancedQueryConditon(String[] array) {
if (Integer.parseInt(array[4]) == 0) {//简单字符
if (array[2].indexOf("IN") != -1)
array[3] = (" ('").concat(array[3]).concat("') ");
else if (array[2].indexOf("LIKE") != -1)
array[3] = (" '%").concat(array[3]).concat("%' ");
else
array[3] = (" '").concat(array[3]).concat("' ");
} else {
if (array[2].indexOf("IN") != -1)
array[3] = (" (").concat(array[3]).concat(") ");
else if (array[2].indexOf("LIKE") != -1)
array[3] = (" '%").concat(array[3]).concat("%' ");
else
array[3] = (" ").concat(array[3]).concat(" ");
}
array[2] = (" ").concat(array[2]).concat(" ");
}

/**
* 字符串内容分析,分析数字的格式化字符串,得到"."后的小数位长度
*
* @param parseStyle 字符串格式
* @return pasreStyleLen 返回“.”以后的字符串长度
*/
private static int parseStyles(String parseStyle) {
int parseStyleLen = 0;
try {
int index = parseStyle.lastIndexOf(".");
parseStyleLen = parseStyle.substring(index + 1).length();
} catch (Exception ex) {
ex.printStackTrace();
}
return parseStyleLen;
}

/**
* 格式化数字字符串,保留两位小数
*
* @param strNumber
* @return
*/
public static String holdDoubleDigit(String strNumber) {
String strTemp = "";
if (isStrEmpty(strNumber))
return strTemp;
if (strNumber.substring(strNumber.length() - 1).equals(GlobalConstant.PERCENTSIGN)) {
strTemp = parseDec(strNumber.substring(0, strNumber.length() - 1));
strTemp = strTemp.concat(GlobalConstant.PERCENTSIGN);
} else {
strTemp = parseDec(strNumber);
}
return strTemp;
}

/**
* 格式化字符串:若为金钱,则格式化成"#,###,###.00";若为小于1的小数,则不变。
*
* @param strMoney
* @return
*/
public static String formatMoneyString(String strMoney) {
if (isStrEmpty(strMoney))
return strMoney;
if (strMoney.indexOf(GlobalConstant.COMMA) != -1)
return strMoney;
if (ValidateUtil.doubleValidate(strMoney.trim())) {
strMoney = strMoney.trim();
if (strMoney.indexOf(GlobalConstant.SPOT) != -1 && strMoney.indexOf(GlobalConstant.SPOT) == strMoney.lastIndexOf(GlobalConstant.SPOT)) {
if (Double.parseDouble(strMoney) < 1d)
return strMoney;
return parseDec(strMoney);
} else
return strMoney;
} else {
return strMoney;
}
}

/**
* 格式化数字字符串,默认格式:##,###,###.00
*
* @param strNumber 数字字符串
* @return 格式后的字符串
*/
public static String parseDec(String strNumber) {
return parseDec(strNumber, null);
}

/**
* 格式化数字字符串,默认格式:##,###,###.00
*
* @param dec 数字字符串
* @param parseStyle 格式
* @return 格式后的字符串
*/
public static String parseDec(String dec, String parseStyle) {
String newObj = "";
DecimalFormat df = null;
try {
if (isStrEmpty(dec)) {
newObj = "";
} else if (!dec.equals("0")) {
if (isStrEmpty(parseStyle))
parseStyle = "##,###,###.00";
// 如果正数大于1或者负数小于1,则根据传入的格式格式化数字
if (Float.parseFloat(dec) >= 1 || Float.parseFloat(dec) <= -1) {
df = new DecimalFormat(parseStyle);
} else {
int parseLen = parseStyles(parseStyle);
StringBuffer parses = new StringBuffer("0.");
for (int i = 0; i < parseLen; i++) {
parses.append("0");
}
df = new DecimalFormat(parses.toString());
}
// 此处不能用Float,否则小数为0;必须用Double或者Long
// 但是Long有可能长度不够
newObj = df.format(new Double(dec));
} else {
newObj = "0.00";
}

} catch (NumberFormatException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
return newObj;
}

/**
* String[][]转换成String
* int index
*
* @param array String数组
* @return null或字符串(多个元素以, 相隔)
*/
public static String stringArrayToString(List array, int index) {
if (array == null)
return null;
if (array.size() == 0)
return null;
StringBuffer sb = new StringBuffer();
for (int i = 0; i < array.size(); i++) {
String[][] str = (String[][]) array.get(i);
sb.append("," + str[0][index]);
}
return sb.substring(1);
}

public static boolean isEmpty(List list) {
boolean isEmpty = Boolean.TRUE;
if (list == null || list.isEmpty())
return isEmpty;
for (Object o : list) {
if (o != null && !StringUtil.isStrEmpty(o.toString())) {
isEmpty = Boolean.FALSE;
break;
}
}
return isEmpty;
}

/**
* 判断是否only展示
*
* @param disabled
* @return true表示只展示不修改
*/
public static boolean isOnlyDisplay(String disabled) {
if ("disabled".equals(disabled) || "yes".equals(disabled) || "true".equals(disabled))
return Boolean.TRUE;
return Boolean.FALSE;
}

public static boolean isNumeric(String str) {
Pattern pattern = Pattern.compile("^(-?[0-9]?[.]?[0-9]+)$");
if (isStrEmpty(str)) {
return false;
} else {
Matcher isNum = pattern.matcher(str);
if (!isNum.matches()) {
return false;
}
}
return true;
}


/**
* 返回四位指标Code,如:0001
*
* @param code
* @return
*/
public static String getIndicatorCode(int code) {
return String.format("%04d", code);
}

public static String specialCharReplace(String paraValue) {
String typeXOne[] = new String[]{"1、", "2、", "3、", "4、", "5、", "6、", "7、", "8、", "9、", "10、", "11、", "12、", "13、", "14、", "15、", "16、", "17、", "18、", "19、", "20、"};
String typeDone[] = new String[]{"一、", "二、", "三、", "四、", "五、", "六、", "七、", "八、", "九、", "十、", "十一、", "十二、", "十三、", "十四、", "十五、", "十六、", "十七、", "十八、", "十九、", "二十、"};
String typeDKOne[] = new String[]{"(一)", "(二)", "(三)", "(四)", "(五)", "(六)", "(七)", "(八)", "(九)", "(十)", "(十一)", "(十二)", "(十三)", "(十四)", "(十五)", "(十六)", "(十七)", "(十八)", "(十九)", "(二十)"};
String typeXDOne[] = new String[]{"1.", "2.", "3.", "4.", "5.", "6.", "7.", "8.", "9.", "10.", "11.", "12.", "13.", "14.", "15.", "16.", "17.", "18.", "19.", "20."};
String typeDKXOne[] = new String[]{"(1)", "(2)", "(3)", "(4)", "(5)", "(6)", "(7)", "(8)", "(9)", "(10)", "(11)", "(12)", "(13)", "(14)", "(15)", "(16)", "(17)", "(18)", "(19)", "(20)"};
if (paraValue.indexOf("、") != -1) {
for (int i = 0; i < typeXOne.length; i++) {
paraValue = paraValue.replace(typeXOne[i], "");
}
for (int i = 0; i < typeDone.length; i++) {
paraValue = paraValue.replace(typeDone[i], "");
}
}
if (paraValue.indexOf("(") != -1) {
for (int i = 0; i < typeDKOne.length; i++) {
paraValue = paraValue.replace(typeDKOne[i], "");
}
for (int i = 0; i < typeDKXOne.length; i++) {
paraValue = paraValue.replace(typeDKXOne[i], "");
}
}
if (paraValue.indexOf(".") != -1) {
for (int i = 0; i < typeXDOne.length; i++) {
paraValue = paraValue.replace(typeXDOne[i], "");
}
}
return paraValue;
}

/**
* 处理下载文件名称
*
* @param fileName
* @return
* @throws java.io.UnsupportedEncodingException
*
*/
public static String encodeFileName(String fileName) throws UnsupportedEncodingException {
// 1 如果长度超出,截取前17个
// fileName.getBytes("gb2312"), "iso8859-1")
String prefix = fileName.substring(0, fileName.lastIndexOf('.'));
String suffix = fileName.substring(fileName.lastIndexOf('.'));
byte[] bytes = fileName.getBytes("gb2312");
String encoded = new String(bytes, "iso8859-1");
return encoded;
}

public static String replaceSpecialChar(String str) {
if (null == str || str.trim().equals("")) {
return "nulltitle";
}
return str.replace("\\/", "").replace("<", "").replace(">", "").replace(":", "").replace("?", "").replace("|", "").replace("\"", "").replace("*", "");
}

/**
* 从指定Map中获取指定Key的 值,并将期值转为String型,若Map中指定Key不存在,则直接返回默认值
*
* @param map Map
* @param key Key
* @param defaultValue 默认值
* @return 将Map值转换后的Integer值,若不存在则返回默认值
*/
public static String convertMapKeyToString(Map<String, String> map, String key, String defaultValue) {
if (map.containsKey(key))
return map.get(key);
else
return defaultValue;
}

/**
* 从指定Map中获取指定Key的值,并将期值转为Integer型,若Map中指定Key不存在,则直接返回0
*
* @param map Map
* @param key Key
* @return 将Map值转换后的Integer值,若不存在则返回0
*/
public static String convertMapKeyToInt(Map<String, String> map, String key) {
return convertMapKeyToString(map, key, "");
}

/**
* 将传入的对象转换为字符串,当传入的对象为null时返回默认值
*
* @param o
* @param dv
* @return
*/
public static String safeToString(Object o, String dv) {
String r = dv;
if (o != null) {
r = String.valueOf(o);
}
return r;
}

/**
* 加密
*
* @param str 字符串
* @return
*/
public static String encrypt(String str, String keystr) {
String _result = null;
// 添加新安全算法 , 如果用 JCE 就要把它添加进去
Security.addProvider(new com.sun.crypto.provider.SunJCE());
String algorithm = "DES";
try {
// 生成密钥
DESKeySpec kds = new DESKeySpec(hex2byte(keystr));
SecretKey deskey = SecretKeyFactory.getInstance(algorithm).generateSecret(kds);
// 加密
Cipher c1 = Cipher.getInstance(algorithm);
c1.init(Cipher.ENCRYPT_MODE, deskey);
byte[] cipherByte = c1.doFinal(str.getBytes());
_result = byte2hex(cipherByte);
} catch (Exception e1) {
}
return _result;
}

/**
* 解密
*
* @param str 字符串
* @return
*/
public static String decrypt(String str, String keystr) {
String _result = null;
Security.addProvider(new com.sun.crypto.provider.SunJCE());
String algorithm = "DES"; // 定义 加密算法 , 可用 DES,DESede,Blowfish
// 解密
byte[] cipherByte = hex2byte(str);
try {
DESKeySpec kds = new DESKeySpec(hex2byte(keystr));
SecretKey deskey = SecretKeyFactory.getInstance(algorithm).generateSecret(kds);
Cipher c1 = Cipher.getInstance(algorithm);
c1.init(Cipher.DECRYPT_MODE, deskey);
byte[] clearByte = c1.doFinal(cipherByte);
_result = new String(clearByte);
} catch (Exception e1) {
}

return _result;
}

public static String byte2hex(byte[] b) {
String hs = "";
String stmp = "";
for (int n = 0; n < b.length; n++) {
stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
if (stmp.length() == 1)
hs = hs + "0" + stmp;
else
hs = hs + stmp;
}
return hs;
}

public static byte[] hex2byte(String str) { // 字符串转二进制
if (str == null)
return null;
str = str.trim();
int len = str.length();
if (len == 0 || len % 2 == 1)
return null;
byte[] b = new byte[len / 2];
try {
for (int i = 0; i < str.length(); i += 2) {
b[i / 2] = (byte) Integer
.decode("0x" + str.substring(i, i + 2)).intValue();
}
return b;
} catch (Exception e) {
return null;
}
}

public static String genKey() {
String _result = null;
// 生成密钥
KeyGenerator keygen = null;
try {
keygen = KeyGenerator.getInstance("DES");
SecretKey deskey = keygen.generateKey();
_result = byte2hex(deskey.getEncoded());
} catch (NoSuchAlgorithmException e) {
//e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}

return _result;
}

/**
* 转半角的函数(DBC case)
* 任意字符串
* 半角字符串
* 全角空格为12288,半角空格为32
* 其他字符半角(33-126)与全角(65281-65374)的对应关系是:均相差65248
*
* @param input
* @return
*/
public static String ToDBC(String input) {
char[] c = input.toCharArray();
for (int i = 0; i < c.length; i++) {
if (c[i] == 12288) {
c[i] = (char) 32;
continue;
}
if (c[i] > 65280 && c[i] < 65375) {
c[i] = (char) (c[i] - 65248);
}
}
return new String(c);
}

public static String escapeHtml(String o) {
return o == null ? "" : o.replace(">", ">").replace(" ", " ").replace("<", "<").replace("\n", "<br/>");
}

/**
* 替换变量。变量是用${...}表示
*
* @param str 字符串
* @param data 数据
* @return
*/
public static String replaceVariables(String str, Map data) {
StringBuffer sb = new StringBuffer();
if (StringUtils.isNotBlank(str)) {
int k = 0;
int j = 0;
int i = str.indexOf("${");
while (i >= 0 && j >= 0) {
sb.append(str.substring(j, i));

j = str.indexOf("}", i);
if (j > 0) {
String name = str.substring(i + 2, j);
if (data.containsKey(name)) {
sb.append(safeToString(data.get(name), ""));
} else {
sb.append("");
}
i = str.indexOf("${", j + 1);
k = j + 1;
j++;
}
}
sb.append(str.substring(k, str.length()));
}
return sb.toString();
}

/**
* 根据条件,截取字符串
*
* @param string 目标字符串
* @param type 截取方式
* @param length 截取长度
* @return 截取的字符串
*/
public static String subStringByLengthAndType(String string, int type, int length) {
return subStringByLengthAndType(string, type, length, 0);
}

/**
* 根据条件,截取字符串
*
* @param string 目标字符串
* @param type 截取方式
* @param length 截取长度
* @param start 截取起点
* @return 截取的字符串
*/
public static String subStringByLengthAndType(String string, int type, int length, int start) {
StringBuffer _string = new StringBuffer();
int _length = 0;
if (type == 0) { //普通截取
if (start + length >= string.length()) {
return string.substring(start);
} else {
return string.substring(start, start + length);
}
} else if (type == 1) { //中文计算2长度截取
for (int i = start; i < string.length() && _length < length; i++) {
if (string.charAt(i) >= 0x7F) {
_length += 2;
} else {
_length++;
}
if (length >= _length) {
_string.append(string.charAt(i));
}
}
}
return _string.toString();
}

/**
* 根据统计方式,获取字符串长度
*
* @param string 目标字符创
* @param type 0为普通方式,1为中文计算两个长度方式
* @return 字符串长度
*/
public static int getStringLengthByType(String string, int type) {
int _length = 0;
if (type == 0) {
return string.length();
} else if (type == 1) {
for (int i = 0; i < string.length(); i++) {
if (string.charAt(i) >= 0x7F) {
_length += 2;
} else {
_length++;
}
}
}
return _length;
}

/**
* 格式化文件大小
*
* @param size
* @return
*/
public static String formatFileSize(double size) {
String[] rank = {"B", "K", "M", "G"};
int c = 0;
while (size > 1024) {
size = size / 1024.0;
c++;
}
DecimalFormat df = new DecimalFormat("0.00");
String result = df.format(size) + (c > rank.length ? rank[rank.length - 1] : rank[c]);

return result;
}

/**
* 关键字搜索
* 检查输入文本text中是否含有keywordList中的关键字
* 返回的List含有搜索到得关键字,未搜索到则返回size为0的List
*
* @param text
* @param keywordList
* @return 返回的List含有搜索到得关键字,未搜索到则返回size为0的List
*/
public static List<String> search(String text, List<String> keywordList) {
List<String> retList = new ArrayList<String>();
if (text == null || "".equals(text)) {
return retList;
}

if (keywordList == null || keywordList.isEmpty()) {
return retList;
}

for (String keyword : keywordList) {
if (keyword == null || "".equals(keyword)) {
continue;
}
if (text.indexOf(keyword) != -1) {
retList.add(keyword);
}
}

return retList;
}

/**
* 关键字搜索
* 检查输入文本text中是否含有keywordList中的关键字
* 返回值中含有搜索到得关键字,以逗号分割,未搜索到则返回null
*
* @param text
* @param keywordList
* @return 返回值中含有搜索到得关键字, 以逗号分割,未搜索到则返回null
*/
public static String searchRetString(String text, List<String> keywordList) {
// List<String> list = search(text, keywordList);
// if(list.isEmpty()) {
// return null;
// }
//
// StringBuilder sb = new StringBuilder();
// for(String s : list) {
// if(sb.length() == 0) {
// sb.append(s);
// } else {
// sb.append(",").append(s);
// }
// }
//
// return sb.toString();


if (text == null || "".equals(text)) {
return null;
}

if (keywordList == null || keywordList.isEmpty()) {
return null;
}

StringBuilder sb = new StringBuilder();
for (String keyword : keywordList) {
if (keyword == null || "".equals(keyword)) {
continue;
}
if (text.indexOf(keyword) != -1) {
if (sb.length() == 0) {
sb.append(keyword);
} else {
sb.append(",").append(keyword);
}
}
}
//System.out.println("searchRetString: " + sb.toString() + sb.length());
return sb.length() == 0 ? null : sb.toString();
}

/**
* 替换字符串中HTML标签
* @param str 字符串
* @return
*/
public static String replaceHtml(String str) {
String pattern1 = "<(.[^>]*)>";
return str.replaceAll(pattern1, "");
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值