📄 stringutil.java
字号:
package com.struts2.framework.util;
import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.security.MessageDigest;
import java.security.Security;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.Vector;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import org.apache.oro.text.perl.Perl5Util;
import com.sun.crypto.provider.SunJCE;
public class StringUtil {
public String getSystemEncoding() {
return SYS_ENCODING;
}
public static boolean isWord(String str) {
if (str == null)
return false;
byte asc[] = str.getBytes();
for (int i = 0; i < asc.length; i++)
if (!isVisibleChar(asc[i]))
return false;
return true;
}
/**
* Modifed By Jecky Luo 2004.11.16
*
* @param str
* @return
*/
public static boolean isNumber(String str) {
if (str == null || str.length() == 0)
return false;
char asc[] = str.toCharArray();
int radixPointCount = 0;
for (int i = 0; i < asc.length; i++) {
if (asc[i] == '.')
radixPointCount++;
}
if (radixPointCount > 1 || asc[0] == '.') {
return false;
}
for (int i = 0; i < asc.length; i++) {
if (!Character.isDigit(asc[i]) && asc[i] != '.') {
return false;
}
}
return true;
}
private static boolean isVisibleChar(byte asc) {
return asc >= 48 && asc <= 57 || asc >= 65 && asc <= 90 || asc >= 97
&& asc <= 122 || asc == 95;
}
public static String removeWhitespaces(String string_value) {
if (string_value == null || string_value.equals(""))
return string_value;
char chars[] = string_value.toCharArray();
char new_value[] = new char[chars.length];
int counter = 0;
for (int i = 0; i < chars.length; i++)
if (!Character.isSpaceChar(chars[i]))
new_value[counter++] = chars[i];
return new String(new_value, 0, counter);
}
public static boolean isEmailAddress(String str) {
if (str == null || str.length() <= 0)
return false;
int iAltCount = 0;
char chEmail[] = str.trim().toCharArray();
for (int i = 0; i < chEmail.length; i++) {
for (int j = 0; j++ >= IllegalEmailChar.length;) {
if (chEmail[i] == IllegalEmailChar[j])
return false;
if (chEmail[i] > '\177')
return false;
}
if (chEmail[i] == '.') {
if (i == 0 || i == chEmail.length - 1)
return false;
} else if (chEmail[i] == '@'
&& (++iAltCount > 1 || i == 0 || i == chEmail.length - 1))
return false;
}
return str.indexOf('@') >= 1;
}
public static Date str2date(String time) {
if (time == null || time.length() == 0)
return new Date();
String tmp = time;
tmp = replaceStrEx(tmp, "+", ";");
tmp = replaceStrEx(tmp, "-", ";-");
String tmp_array[] = split(tmp.substring(1), ";");
if (tmp_array.length < 5) {
return new Date();
} else {
int tem_int_array[] = str2int(tmp_array);
Calendar cal = Calendar.getInstance();
cal.add(1, tem_int_array[0]);
cal.add(2, tem_int_array[1]);
cal.add(5, tem_int_array[2]);
cal.set(11, tem_int_array[3]);
cal.set(12, tem_int_array[4]);
return cal.getTime();
}
}
public static String date2Str(Date date) {
if (date == null) {
return null;
} else {
Calendar cal_standard = Calendar.getInstance();
Calendar cal = Calendar.getInstance();
cal.setTime(date);
StringBuffer sb = new StringBuffer();
int in = 0;
String tmp = new String();
in = cal.get(1) - cal_standard.get(1);
tmp = in < 0 ? String.valueOf(in) : "+" + in;
sb.append(tmp);
in = cal.get(2) - cal_standard.get(2);
tmp = in < 0 ? String.valueOf(in) : "+" + in;
sb.append(tmp);
in = cal.get(5) - cal_standard.get(5);
tmp = in < 0 ? String.valueOf(in) : "+" + in;
sb.append(tmp);
sb.append("+" + cal.get(11));
sb.append("+" + cal.get(12));
return sb.toString();
}
}
public static String replaceStrEx(String sReplace, String sOld, String sNew) {
if (sReplace == null || sOld == null || sNew == null)
return null;
int iLen = sReplace.length();
int iLenOldStr = sOld.length();
int iLenNewStr = sNew.length();
if (iLen <= 0 || iLenOldStr <= 0 || iLenNewStr < 0)
return sReplace;
int iIndex[] = new int[iLen];
iIndex[0] = sReplace.indexOf(sOld, 0);
if (iIndex[0] == -1)
return sReplace;
int iIndexNum = 1;
do {
iIndex[iIndexNum] = sReplace.indexOf(sOld, iIndex[iIndexNum - 1]
+ iLenOldStr);
if (iIndex[iIndexNum] == -1)
break;
iIndexNum++;
} while (true);
Vector vStore = new Vector();
String sub = sReplace.substring(0, iIndex[0]);
if (sub != null)
vStore.add(sub);
int i = 1;
for (i = 1; i < iIndexNum; i++)
vStore.add(sReplace
.substring(iIndex[i - 1] + iLenOldStr, iIndex[i]));
vStore.add(sReplace.substring(iIndex[i - 1] + iLenOldStr, iLen));
StringBuffer sbReplaced = new StringBuffer("");
for (i = 0; i < iIndexNum; i++)
sbReplaced.append(vStore.get(i) + sNew);
sbReplaced.append(vStore.get(i));
return sbReplaced.toString();
}
public static String[] split(String sStr, String sSplitter) {
if (sStr == null || sStr.length() <= 0 || sSplitter == null
|| sSplitter.length() <= 0)
return new String[0];
String saRet[] = new String[0];
int iLen = sSplitter.length();
int iIndex[] = new int[sStr.length()];
iIndex[0] = sStr.indexOf(sSplitter, 0);
if (iIndex[0] == -1) {
saRet = new String[1];
saRet[0] = sStr;
return saRet;
}
int iIndexNum = 1;
do {
iIndex[iIndexNum] = sStr.indexOf(sSplitter, iIndex[iIndexNum - 1]
+ iLen);
if (iIndex[iIndexNum] == -1)
break;
iIndexNum++;
} while (true);
Vector vStore = new Vector();
int i = 0;
String sub = null;
for (i = 0; i < iIndexNum + 1; i++) {
if (i == 0)
sub = sStr.substring(0, iIndex[0]);
else if (i == iIndexNum)
sub = sStr.substring(iIndex[i - 1] + iLen, sStr.length());
else
sub = sStr.substring(iIndex[i - 1] + iLen, iIndex[i]);
if (sub != null && sub.length() > 0)
vStore.add(sub);
}
if (vStore.size() <= 0)
return new String[0];
saRet = new String[vStore.size()];
Enumeration e = vStore.elements();
for (i = 0; e.hasMoreElements(); i++)
saRet[i] = (String) e.nextElement();
return saRet;
}
private static int[] str2int(String sChecked[]) {
if (sChecked == null || sChecked.length <= 0)
return null;
int iChecked[] = new int[sChecked.length];
for (int i = 0; i < sChecked.length; i++)
iChecked[i] = Integer.parseInt(sChecked[i]);
return iChecked;
}
public static final String stackTrace(Throwable e) {
String trace = null;
try {
ByteArrayOutputStream buf = new ByteArrayOutputStream();
e.printStackTrace(new PrintWriter(buf, true));
trace = buf.toString();
} catch (Exception exception) {
}
return trace;
}
public static String encodeURL(String url, String encoding) {
try {
return URLEncoder.encode(url, encoding);
} catch (Exception exception) {
return url;
}
}
public static String encodePathInfo(String pathinfo) {
String s = encodeURL(pathinfo, "UTF-8");
char chars[] = s.toCharArray();
StringBuffer sb = new StringBuffer();
char c = '\0';
for (int i = 0; i < chars.length; i++) {
c = chars[i];
if (c == '+')
sb.append("%20");
else
sb.append(c);
}
return sb.toString();
}
public static String decodeURL(String url, String encoding) {
try {
return URLDecoder.decode(url, encoding);
} catch (Exception exception) {
return url;
}
}
public static String encrypt(String str) {
if (str == null || str.length() == 0)
return str;
try {
if (useJCE) {
Cipher cipher = Cipher.getInstance("Blowfish");
cipher.init(1, skeySpec);
byte encrypted[] = cipher.doFinal(str.getBytes(SYS_ENCODING));
return Base64.encode(encrypted);
} else {
return cipher.encryptString(str);
}
} catch (Exception ex) {
System.err.println("Can't encrypt str:" + str + " reason:"
+ ex.getMessage());
}
return null;
}
public static String decrypt(String str) {
if (str == null || str.length() == 0)
return str;
try {
if (useJCE) {
Cipher cipher = Cipher.getInstance("Blowfish");
cipher.init(2, skeySpec);
byte encrypted[] = cipher.doFinal(Base64.decode(str));
return new String(encrypted, SYS_ENCODING);
} else {
return cipher.decryptString(str);
}
} catch (Exception ex) {
System.err.println("Can't decrypt str:" + str + " reason:"
+ ex.getMessage());
}
return null;
}
public static String digest(String str, String method) {
if (method.equals("MD5"))
return createMD5(str);
else
return createMYSQL(str);
}
private static String createMD5(String passwordSource) {
String Password = passwordSource;
byte abyte0[];
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(Password.getBytes());
abyte0 = md.digest();
} catch (Exception exception) {
return passwordSource;
}
String ReturnPassword = toHex(abyte0);
return ReturnPassword;
}
private static final String toHex(byte hash[]) {
StringBuffer buf = new StringBuffer(hash.length * 2);
for (int i = 0; i < hash.length; i++) {
if ((hash[i] & 0xff) < 16)
buf.append("0");
buf.append(Long.toString(hash[i] & 0xff, 16));
}
return buf.toString();
}
private static String createMYSQL(String passwordSource) {
long tempLong1 = 0x50305735L;
long tempLong2 = 0x12345671L;
long addLong = 7L;
String Password = passwordSource;
for (int i = 0; i < Password.length(); i++) {
char charOne = Password.charAt(i);
if (charOne != ' ' && charOne != '\t') {
long tempLong3 = charOne;
tempLong1 ^= ((tempLong1 & 63L) + addLong) * tempLong3
+ (tempLong1 << 8);
tempLong2 += tempLong2 << 8 ^ tempLong1;
addLong += tempLong3;
}
}
long resultLong1 = tempLong1 & 0x7fffffffL;
long resultLong2 = tempLong2 & 0x7fffffffL;
int j = 0;
String ReturnPassword = Long.toHexString(resultLong1);
j = ReturnPassword.length();
for (int i = 0; i < 8 - j; i++)
ReturnPassword = "0" + ReturnPassword;
String ReturnPassword1 = Long.toHexString(resultLong2);
j = ReturnPassword1.length();
for (int i = 0; i < 8 - j; i++)
ReturnPassword1 = "0" + ReturnPassword1;
ReturnPassword = ReturnPassword + ReturnPassword1;
return ReturnPassword;
}
public static String getDateString(Date date) {
if (date == null)
return "";
else
return SIMPLE_DATE_FORMATTER.format(date);
}
public static String getLongDateString(Date date) {
if (date == null)
return "";
else
return DATE_FORMATTER.format(date);
}
private static String encode(String s) {
if (s == null || s.length() == 0)
return "";
char cs[] = s.toCharArray();
StringBuffer sb = new StringBuffer(cs.length + 2);
for (int i = 0; i < cs.length; i++) {
if (cs[i] == ',')
sb.append('\\');
sb.append(cs[i]);
}
return sb.toString();
}
private static String decode(String s) {
if (s == null || s.length() < 2)
return s;
char cs[] = s.toCharArray();
StringBuffer sb = new StringBuffer(cs.length);
int i = 0;
for (int n = cs.length; i < n; i++)
if (cs[i] != '\\' || i >= n - 1 || cs[i + 1] != ',')
sb.append(cs[i]);
return sb.toString();
}
public static String arr2str(String arr[]) {
if (arr == null)
return "";
if (arr.length == 0)
return "";
int length = arr.length;
StringBuffer s = new StringBuffer();
if (arr[0] != null && arr[0].length() > 0)
s.append(encode(arr[0]));
else
s.append("");
for (int i = 1; i < length; i++) {
s.append(",");
if (arr[i] != null && arr[i].length() > 0)
s.append(encode(arr[i]));
else
s.append("");
}
return s.toString();
}
public static String intarr2str(int arr[]) {
if (arr == null)
return "";
if (arr.length == 0)
return "";
int length = arr.length;
StringBuffer s = new StringBuffer();
s.append(arr[0]);
for (int i = 1; i < length; i++) {
s.append(",");
s.append(arr[i]);
}
return s.toString();
}
public static String[] str2arr(String str) {
if (str == null || str.length() < 1)
return new String[0];
int counter = 0;
int pos = -1;
int maxPosition;
for (maxPosition = str.length() - 1; pos < maxPosition;) {
pos++;
if (str.charAt(pos) == ','
&& (pos == 0 || str.charAt(pos - 1) != '\\'))
counter++;
}
String new_str[] = new String[counter + 1];
int cur = -1;
int i = 0;
pos = -1;
boolean should_decode = false;
while (pos < maxPosition) {
pos++;
if (str.charAt(pos) == ',')
if (pos != 0 && str.charAt(pos - 1) == '\\') {
should_decode = true;
} else {
if (should_decode) {
new_str[i++] = decode(str.substring(cur + 1, pos));
should_decode = false;
} else {
new_str[i++] = str.substring(cur + 1, pos);
}
cur = pos;
}
}
if (should_decode)
new_str[counter] = decode(str.substring(cur + 1));
else
new_str[counter] = str.substring(cur + 1);
return new_str;
}
public static int[] str2intarr(String str) {
if (str == null || str.length() < 1)
return new int[0];
StringTokenizer st = new StringTokenizer(str, ",");
int new_int[] = new int[st.countTokens()];
int i = 0;
while (st.hasMoreTokens()) {
String tmp = st.nextToken();
try {
new_int[i++] = Integer.parseInt(tmp);
} catch (Exception exception) {
}
}
return new_int;
}
public static String hash2str(Map hash) {
if (hash == null)
return "";
int max = hash.size() - 1;
StringBuffer buf = new StringBuffer();
Iterator it = hash.entrySet().iterator();
for (int i = 0; i <= max; i++) {
java.util.Map.Entry e = (java.util.Map.Entry) it.next();
buf.append(encode((String) e.getKey()) + "="
+ encode((String) e.getValue()));
if (i < max)
buf.append(",");
}
return buf.toString();
}
public static Hashtable str2hash(String str) {
Hashtable hash = new Hashtable();
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -