package com.saicfc.saicifx3.util; import java.awt.FontMetrics; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.math.BigDecimal; import java.math.RoundingMode; import java.text.DecimalFormat; import java.text.ParsePosition; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Random; import java.util.StringTokenizer; import java.util.regex.Pattern; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * String Utility Class This is used to encode passwords programmatically * * <p> * <a h ref="StringUtil.java.html"><i>View Source</i></a> * </p> * * @author <a href="mailto:[email protected]">Matt Raible</a> */ public class StringUtil { // ~ Static fields/initializers // ============================================= private final static Log log = LogFactory.getLog(StringUtil.class); private static DecimalFormat decimalFormat = new DecimalFormat("#,###,###,###.##"); // ~ Methods // ================================================================ /** * Encode a string using Base64 encoding. Used when storing passwords as * cookies. * * This is weak encoding in that anyone can use the decodeString routine to * reverse the encoding. * * @param str * @return String */ public static String encodeString(String str) { sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder(); return encoder.encodeBuffer(str.getBytes()).trim(); } /** * Decode a string using Base64 encoding. * * @param str * @return String */ public static String decodeString(String str) { sun.misc.BASE64Decoder dec = new sun.misc.BASE64Decoder(); try { return new String(dec.decodeBuffer(str)); } catch (IOException io) { throw new RuntimeException(io.getMessage(), io.getCause()); } } // Deprecated public static String replace(String str, String srcStr, String desStr) { String returnValue = ""; String temp = ""; int start = str.indexOf(srcStr); int len = srcStr.length(); while (start > -1) { temp = str.substring(0, start); returnValue = returnValue + temp + desStr; str = str.substring(start + len); start = str.indexOf(srcStr); } returnValue = returnValue + str; return returnValue; } // 以flag为标记,把str分割为String数组。 public static String[] getStringArra(String str, String flag) { String[] result = null; StringTokenizer tem = new StringTokenizer(str, flag); int n = tem.countTokens(); result = new String[n]; for (int i = 0; tem.hasMoreTokens(); i++) result[i] = tem.nextToken(); return result; } public static String[] trim(String[] paramArray) { if (ArrayUtils.isEmpty(paramArray)) { return paramArray; } String[] resultArray = new String[paramArray.length]; for (int i = 0; i < paramArray.length; i++) { String param = paramArray[i]; resultArray[i] = StringUtils.trim(param); } return resultArray; } public static int CHINESECHARTYPE = 0; public static int ENGLISHCHARTYPE = 1; public static String LEFT = "l"; public static String CENTER = "0"; public static String RIGHT = "r"; public static String __ISO_8859_1; static { String iso = System.getProperty("ISO_8859_1"); if (iso != null) { __ISO_8859_1 = iso; } else { try { new String(new byte[] { (byte) 20 }, "ISO-8859-1"); __ISO_8859_1 = "ISO-8859-1"; } catch (java.io.UnsupportedEncodingException e) { __ISO_8859_1 = "ISO8859_1"; } } } private static char[] lowercases = { '\000', '\001', '\002', '\003', '\004', '\005', '\006', '\007', '\010', '\011', '\012', '\013', '\014', '\015', '\016', '\017', '\020', '\021', '\022', '\023', '\024', '\025', '\026', '\027', '\030', '\031', '\032', '\033', '\034', '\035', '\036', '\037', '\040', '\041', '\042', '\043', '\044', '\045', '\046', '\047', '\050', '\051', '\052', '\053', '\054', '\055', '\056', '\057', '\060', '\061', '\062', '\063', '\064', '\065', '\066', '\067', '\070', '\071', '\072', '\073', '\074', '\075', '\076', '\077', '\100', '\141', '\142', '\143', '\144', '\145', '\146', '\147', '\150', '\151', '\152', '\153', '\154', '\155', '\156', '\157', '\160', '\161', '\162', '\163', '\164', '\165', '\166', '\167', '\170', '\171', '\172', '\133', '\134', '\135', '\136', '\137', '\140', '\141', '\142', '\143', '\144', '\145', '\146', '\147', '\150', '\151', '\152', '\153', '\154', '\155', '\156', '\157', '\160', '\161', '\162', '\163', '\164', '\165', '\166', '\167', '\170', '\171', '\172', '\173', '\174', '\175', '\176', '\177' }; public static String asciiToLowerCase(String s) { char[] c = s.toCharArray(); for (int i = c.length; i-- > 0;) { if (c[i] <= 127) { c[i] = lowercases[c[i]]; } } return (new String(c)); } public static int indexFrom(String s, String chars) { for (int i = 0; i < s.length(); i++) { if (chars.indexOf(s.charAt(i)) >= 0) { return i; } } return -1; } public static String _replace(String s, String sub, String with) { int c = 0; int i = s.indexOf(sub, c); if (i == -1) { return s; } StringBuffer buf = new StringBuffer(s.length() + with.length()); synchronized (buf) { do { buf.append(s.substring(c, i)); buf.append(with); c = i + sub.length(); } while ((i = s.indexOf(sub, c)) != -1); if (c < s.length()) { buf.append(s.substring(c, s.length())); } return buf.toString(); } } public static String unquote(String s) { if ((s.startsWith("\"") && s.endsWith("\"")) || (s.startsWith("'") && s.endsWith("'"))) { s = s.substring(1, s.length() - 1); } return s; } public static void append(StringBuffer buf, String s, int offset, int length) { synchronized (buf) { int end = offset + length; for (int i = offset; i < end; i++) { if (i >= s.length()) { break; } buf.append(s.charAt(i)); } } } public static String nonNull(String s) { if (s == null) { return ""; } return s; } private static String[] ZEROS = { "", "0", "00", "000", "0000", "00000", "000000", "0000000", "00000000", "000000000" }; public static String[] CHINESECHAR = { "", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二", "十三", "十四", "十五", "十六", "十七", "十八", "十九", "二十", "二十一", "二十二", "二十三", "二十四", "二十五", "二十六", "二十七", "二十八", "二十九", "三十", "三十一", "三十二", "三十三", "三十四", "三十五", "三十六", "三十七", "三十八", "三十九" }; public static String[] ENGLISHCHAR = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" }; static public String retrimString(String str, int maxlength) { int theLen = 0; str = str.trim(); int i = 0; int size = str.getBytes().length; byte[] temp = str.getBytes(); if (size > maxlength) { for (i = 0; i < size; i++) { if (temp[i] > 255) { if (theLen > maxlength) { theLen = theLen - 2; break; } else { theLen = theLen + 2; } } else { if (theLen > maxlength) { theLen = theLen - 1; break; } else { theLen = theLen + 1; } } } str = new String(str.getBytes(), 0, i); } return str; } static public String breakLine(String str) { if (str != null && str.length() > 0) { StringBuffer sb = new StringBuffer(str); int beginPos = -1; while ((beginPos = str.indexOf('\n')) > -1) { sb.replace(beginPos, beginPos + 1, "<br>"); str = sb.toString(); } str = replace(sb.toString(), " ", ""); } return str; } /*************************************************************************** * String methods. * * **************************************************************************/ /** * 将一个字符串以某字符作为分隔符进行分隔(得到每段作为字符串的字符串数组). * * @param str * 被分隔的字符串 * @param delimiter * 分隔符 * @return 分隔的结果 */ public final static String[] splitString(String str, char delimiter) { return splitString(str, 0, delimiter); } public final static String[][] splitString(String str, char delimiter1, char delimiter2) { String[] a1 = splitString(str, delimiter1); if (a1 == null) { return null; } String a2[][] = new String[a1.length][]; for (int i = 0; i < a1.length; i++) { a2[i] = splitString(a1[i], delimiter2); } return a2; } /** * 将一个字符串从某位置开始以某字符作为分隔符进行分隔(得到每段作为字符串的字符串数组). <blockquote> * * <pre> * String list[] = Utilities.splitString("AAAA,BBBB,CCCC,DDDDD",0,',') * // list 为 { "AAAA","BBBB","CCCC","DDDD" } * </pre> * * </blockquote> * * @param str * 被分隔的字符串 * @param istart * 开始位置 * @param delimiter * 分隔符 * @return 分隔的结果 */ public final static String[] splitString(String str, int istart, char delimiter) { if (str == null) { return null; } int sl = str.length(); int n = 0; for (int i = istart; i < sl; i++) { if (str.charAt(i) == delimiter) { n++; } } String[] sa = new String[n + 1]; int i = istart, j = 0; for (; i < sl;) { int iend = str.indexOf(delimiter, i); if (iend < 0) { break; } sa[j++] = str.substring(i, iend); i = iend + 1; } sa[j++] = str.substring(i); return sa; } public static int getSubstringByLength(String[] text, int startIndex, int width, FontMetrics metrics) { int endIndex = startIndex; int index = 0; int size = text.length; int sumWidth = 0; for (index = startIndex; index < size; ++index) { sumWidth += metrics.stringWidth(text[index]); if (sumWidth == width) { endIndex = index; break; } else if (sumWidth > width) { endIndex = index - 1; break; } } if (index == size) { endIndex = size - 1; } return endIndex; } // 包含copy,startIndex,endIndex包含在获得的子串中 public static String substring(String[] text, int startIndex, int endIndex) { StringBuffer sb = new StringBuffer(); int index = 0; for (index = startIndex; index <= endIndex; ++index) { sb.append(text[index]); } return sb.toString(); } // 包含copy,startIndex包含在获得的子串中 public static String substring(String[] text, int startIndex) { StringBuffer sb = new StringBuffer(); int index = 0; int size = text.length; for (index = startIndex; index < size; ++index) { sb.append(text[index]); } return sb.toString(); } public static final String[] splitString(String s) { if (s == null) { return null; } int size = s.length(); int index = 0; String as[] = new String[size]; for (index = 0; index < size; ++index) { as[index] = s.substring(index, index + 1); } return as; } public static int findAtStringArray(String as[], Object obj) { if (as != null) { for (int i = 0; i < as.length; i++) { if (obj == as[i] || obj != null && obj.equals(as[i])) { return i; } } } return -1; } public static int findAtStringArrayNoCase(String as[], String s) { if (as != null) { for (int i = 0; i < as.length; i++) { if (s == as[i] || s != null && s.equalsIgnoreCase(as[i])) { return i; } } } return -1; } public final static String unicode2gb(String value) throws UnsupportedEncodingException { return new String(value.getBytes(), "GB2312"); } public final static String gb2unicode(String value) throws UnsupportedEncodingException { return new String(value.getBytes("GB2312")); } public final static String gb2iso(String value) { if (value == null || value.trim().equals("")) { return ""; } return value; } public final static String iso2gb(String value) { if (value == null || value.trim().equals("")) { return ""; } try { return new String(value.getBytes("ISO8859_1"), "GBK"); } catch (UnsupportedEncodingException ex) { ex.printStackTrace(); return ex.getMessage(); } } public final static String firstCapital(String value) { if (value == null) { return ""; } else { return value.substring(0, 1).toUpperCase() + value.substring(1); } } public final static String emitValue(String value, boolean isShow) { if ((value == null) || (value.trim().equals(""))) { if (isShow) { return ""; } else { return ""; } } else { return gb2iso(value); } } public final static String emitValue(String value, boolean isConvert, boolean isShow) { if ((value == null) || (value.trim().equals(""))) { if (isShow) { return ""; } else { return ""; } } else { if (isConvert) { return gb2iso(value); } else { return value; } } } public static String toPaddedString(String s, int length) { return ZEROS[length - s.length()] + s; } public static String toPaddedString(String s, String padChar, int length, String alignment) { int size = s.length(); int index = 0; if (size >= length) { return s; } else { int subLen = length - size; StringBuffer sb = new StringBuffer(); for (index = 0; index < subLen; ++index) { sb.append(padChar); } if (alignment.equals(LEFT)) { return s + sb.toString(); } else if (alignment.equals(RIGHT)) { return sb.toString() + s; } else { return s; } } } public static String convert(int countType, int index) { ++index; int head = 0; int remain = 0; String value = ""; if (countType == CHINESECHARTYPE) { head = index / 10; remain = index % 10; if (head > 0) { if (head > 1) { value = CHINESECHAR[head]; } value += "十"; } // if(remain>0) value += CHINESECHAR[remain]; return value; } else if (countType == ENGLISHCHARTYPE) { if (index >= ENGLISHCHAR.length) { return ""; } else { return ENGLISHCHAR[index]; } } else { return ""; } } static public String digit2Char(String digit) { String value = ""; String sub = null; int index = 0; int size = digit.length(); for (index = 0; index < size; ++index) { sub = digit.substring(index, index + 1); value += ENGLISHCHAR[Integer.parseInt(sub)]; } return value; } static public String getPRN() { Calendar rightNow = Calendar.getInstance(); Random random = new Random(rightNow.getTime().getTime()); long value = Math.abs(random.nextLong()); String key = StringUtil.digit2Char(String.valueOf(value)); return key; } static public boolean checkBoundary(String preValue, String currValue) { if (preValue == null) { return false; } else { if (preValue.equals(currValue)) { return false; } else { return true; } } } static public String escapeConvert(String value) { HashMap<String, String> term = new HashMap<String, String>(); // term.put("&","&"); term.put("<", "<"); term.put(">", ">"); term.put("\"", """); term.put("'", "'"); value = replace(value, "&", "&"); Iterator iterator = term.keySet().iterator(); String key = null; String escape = null; while (iterator.hasNext()) { key = (String) iterator.next(); escape = (String) term.get(key); value = replace(value, key, escape); } return value; } // 在指定的长度的位置增加一个标记字符 static public String append(String value, String tag, int subLen) { int size = value.length() / subLen; int index = 0; StringBuffer sb = new StringBuffer(); for (index = 0; index < size; ++index) { sb.append(value.substring(index * subLen, (index + 1) * subLen)); sb.append(tag); } // 处理最后的尾数 size = value.length() % subLen; sb.append(value.substring(index * subLen, index * subLen + size)); sb.append(tag); return sb.toString(); } // 序列号web输出 static public String seriesWebEmit(int size, String format) { int index = 0; StringBuffer sb = new StringBuffer(); for (index = 0; index < size; ++index) { sb.append("<option value=\""); sb.append(index); sb.append("\">"); sb.append(StringUtil.replace(format, "DD", String.valueOf(index + 1))); sb.append("</option> \r\n"); } return sb.toString(); } /* 模糊匹配 */ public static boolean matchIP(String templete, String value) { StringTokenizer templeteST = new StringTokenizer(templete + ".", "."); StringTokenizer valueST = new StringTokenizer(value + ".", "."); String s = null; String sub = null; boolean result = true; while (templeteST.hasMoreElements()) { s = (String) templeteST.nextElement(); sub = (String) valueST.nextElement(); if (s.indexOf("*") > -1) { continue; } else { if (!s.equals(sub)) { result = false; break; } } } return result; } // 对字符串进行缩略处理 static public String breviary(String value, String breviaryTag, int subLen) { if (value.length() <= subLen) return value; else { return value.substring(0, subLen) + breviaryTag; } } public static String formatCurrency(BigDecimal bigDecimal) { if (bigDecimal == null) { return null; } return decimalFormat.format(bigDecimal.setScale(2, RoundingMode.HALF_UP)); } public static String format(Object o, String pattern) { if (o == null) { o = 0; } DecimalFormat format = new DecimalFormat(pattern); return format.format(o); } public static BigDecimal parseCurrency(String bigDecimalStr) { decimalFormat.setParseBigDecimal(true); if (StringUtils.isBlank(bigDecimalStr)) { return null; } BigDecimal bigDecimal = null; try { bigDecimal = (BigDecimal) decimalFormat.parse(bigDecimalStr, new ParsePosition(0)); } catch (Exception e) { return null; } return bigDecimal.setScale(2, RoundingMode.HALF_UP); } /** * 分割字符串({\d})并替换 * * @param value * @param obj * @return */ public static String splitReplaceParam(String value, Object[] obj) { List<String> list = new ArrayList<String>(); String[] s = value.split("\\{"); for (int i = 1; i < s.length; i++) { if (s[i].indexOf("}") < 0) { continue; } String key = s[i].substring(0, s[i].indexOf("}")); if (list.isEmpty()) { list.add(key); } else if (!list.contains(key)) { list.add(key); } } Collections.sort(list); Object[] obj1 = list.toArray(); for (int i = 0; i < obj.length; i++) { value = value.replaceAll("\\{" + obj1[i] + "}", String.valueOf(obj[i])); } return value; } /** * 返回16位数字:请14为年月日时分秒,后2位随机 * * @return */ public static String getRandomNum() { Date date = new Date(); return new StringBuilder().append(DateUtil.formatDateToString(date, "yyyyMMddHHmmss")) .append(Math.round(Math.random() * date.getTime())).substring(0, 16); } /** * 全角符号替换成半角符号 * @param QJstr * @return */ public static String full2HalfChange(String QJstr) { StringBuffer outStrBuf = new StringBuffer(""); String Tstr = ""; byte[] b = null; for (int i = 0; i < QJstr.length(); i++) { Tstr = QJstr.substring(i, i + 1); // 全角空格转换成半角空格 if (Tstr.equals(" ")) { outStrBuf.append(" "); continue; } try { b = Tstr.getBytes("unicode"); // 得到unicode字节数据 if (b[2] == -1) { // 表示全角 b[3] = (byte) (b[3] + 32); b[2] = 0; outStrBuf.append(new String(b, "unicode")); } else { outStrBuf.append(Tstr); } } catch (UnsupportedEncodingException ex) { ex.printStackTrace(); return ex.getMessage(); } } return outStrBuf.toString(); } /** * 判断字符串是否为数字 * @param str * @return */ public static boolean isNumeric(String str) { Pattern pattern = Pattern.compile("[0-9]*"); return pattern.matcher(str).matches(); } /** * 判断字符串是否为英文字母 * @param str * @return */ public static boolean strIsEnglish(String str) { Pattern pattern = Pattern.compile("^[a-zA-Z]*"); return pattern.matcher(str).matches(); } /** mapList转为数组List */ public static List getArraysList(List<?> list, String... key) { List<Object> resultList = InstanceUtils.newArrayList(); for (Iterator iterator = list.iterator(); iterator.hasNext();) { Map map = (Map) iterator.next(); Object[] temp = new Object[key.length]; for (int i = 0; i < temp.length; i++) { temp[i] = map.get(key[i]); } resultList.add(temp); } return resultList; } }