/**
* @file: Tools.java
* 常用工具方法类.
*/
package cn.com.pubwin.police.core.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.net.InetAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import java.util.TimeZone;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
import com.individual.common.utils.StringUtils;
import com.opensymphony.oscache.util.StringUtil;
import cn.com.pubwin.police.util.GlobalKeys;
/**
* 常用工具函数类. 用静态函数的方法定义一些常用的函数,如字符串转数字、字符串转日期等。
*/
public class Tools {
/* ================== 以下定义公有属性和方法 ================== */
public static final SimpleDateFormat FULL_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static final SimpleDateFormat FULL_YMD_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
public static final SimpleDateFormat FULL_TIME_FORMAT = new SimpleDateFormat("HH:mm:ss");
private static final Pattern numPattern = Pattern.compile("[0-9]*");
private static final Pattern numLetterPattern = Pattern.compile("[0-9a-zA-Z]*");
private static final Pattern hexPattern = Pattern.compile("[0-9a-fA-F]*");
private static final Pattern sentencePattern = Pattern.compile("[,,;;。\u002E\t\n\r]");
private static final Pattern fileTypePattern = Pattern.compile("\\.\\w+$");
public static final SimpleDateFormat FULL_YM_FORMAT = new SimpleDateFormat("yyyy-M");
public static final SimpleDateFormat FULL_YMDDATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
/**
* 将UNICODE表示的字符串转换为国标码.
*
* @param strValue:需要转换的字符串。
* @return 返回转换好的字符串,如果strValue为空,返回null。
*/
public static String getGBString(String strValue) {
if (strValue == null)
return null;
String strGBValue = null;
try {
strGBValue = new String(strValue.getBytes("ISO-8859-1"), "gbk");
} catch (UnsupportedEncodingException e) {
strGBValue = null;
}
return strGBValue;
}
/** 字符串转长整数,且不抛出异常,出错则返回0 */
public static long str2long(String strValue) {
if (strValue == null)
return 0L;
long nValue = 0;
try {
String temp = strValue.trim();
nValue = Long.parseLong(temp);
} catch (NumberFormatException e) {
// do nothing
}
return nValue;
}
/** 字符串转整数,且不抛出异常,出错则返回0 */
public static int str2intOld(String strValue) {
if (strValue == null)
return 0;
int nValue = 0;
try {
String temp = strValue.trim();
nValue = (new Double(temp)).intValue();
} catch (NumberFormatException e) {
// do nothing
}
return nValue;
}
/** 字符串转整数,不抛出异常,出错返回缺省值 */
public static int str2intOld(String strValue, int nDefault) {
int nValue = nDefault;
if (strValue == null)
return nValue;
try {
String temp = strValue.trim();
nValue = (new Double(temp)).intValue();
} catch (NumberFormatException e) {
nValue = nDefault;
}
return nValue;
}
/** 字符串转整数,且抛出异常 */
public static int str2intEx(String strValue) throws NumberFormatException {
if (strValue == null)
throw new NumberFormatException("字符串为空");
int nValue = 0;
String temp = strValue.trim();
nValue = (new Double(temp)).intValue();
return nValue;
}
/** 字符串转浮点数,且不抛出异常,出错则返回0 */
public static double str2double(String strValue) {
if (strValue == null)
return 0;
double nValue = 0;
try {
String temp = strValue.trim();
nValue = Double.parseDouble(temp);
} catch (NumberFormatException e) {
// do nothing
}
return nValue;
}
/** 字符串转浮点数,不抛出异常,出错返回缺省值 */
public static double str2double(String strValue, double nDefault) {
double nValue = nDefault;
if (strValue == null)
return nValue;
if (strValue.equals(""))
return nValue;
try {
String temp = strValue.trim();
nValue = Double.parseDouble(temp);
} catch (NumberFormatException e) {
// do nothing
}
return nValue;
}
/** 字符串转日期型,且不抛出异常,出错返回1970-1-1 0:0:0 */
public static Calendar str2calendar(String strValue) {
if (strValue == null)
return null;
Calendar theDate;
try {
String str = strValue.substring(4, 5);
SimpleDateFormat theFormat = new SimpleDateFormat("yyyy" + str + "MM" + str + "dd");
theFormat.parse(strValue);
theDate = theFormat.getCalendar();
} catch (ParseException ex) {
theDate = null;
} catch (IndexOutOfBoundsException ex) {
theDate = null;
}
return theDate;
}
/** 长日期字符串转date型 */
public static Date str2date(String strValue) {
if (strValue == null)
return null;
Date theDate;
if (strValue.equals(""))
return null;
try {
String str = strValue.substring(4, 5);
SimpleDateFormat theFormat = new SimpleDateFormat("yyyy" + str + "MM" + str + "dd" + " " + "HH" + ":"
+ "mm" + ":" + "ss");
theDate = theFormat.parse(strValue);
} catch (Exception ex) {
theDate = null;
}
return theDate;
}
/** 长日期字符串格式化成yyyy-mm-dd后转成字符串输出 */
public static String strdate2str(String strValue) {
if (strValue != null && !strValue.equals("")) {
return FULL_YMD_FORMAT.format(Tools.str2date(strValue));
} else {
return ("");
}
}
/** 短日期字符串格式化成yyyy-mm-dd后转成字符串输出 */
public static String shortstrdate2str(String strValue) {
if (strValue != null && !strValue.equals("")) {
return FULL_YMD_FORMAT.format(Tools.shortstr2date(strValue));
} else {
return ("");
}
}
/** 短日期字符串转date型 */
public static Date shortstr2date(String strValue) {
if (strValue == null)
return null;
Date theDate;
if (strValue.equals(""))
return null;
try {
String str = strValue.substring(4, 5);
SimpleDateFormat theFormat = new SimpleDateFormat("yyyy" + str + "MM" + str + "dd");
theDate = theFormat.parse(strValue);
} catch (Exception ex) {
theDate = null;
}
return theDate;
}
/** 时间字符串转date型 */
public static Date timeStr2date(String strValue) {
if (strValue == null || strValue.equals("")) {
return null;
}
Date theDate;
try {
theDate = Tools.FULL_TIME_FORMAT.parse(strValue);
} catch (Exception ex) {
theDate = null;
}
return theDate;
}
/** 判断短日期字符串是否是日期格式 */
public static boolean isDate(String strValue) {
Date checkdate = shortstr2date(strValue);
if (checkdate != null) {
return true;
} else {
return false;
}
}
/** 判断长日期字符串是否是日期格式 */
public static boolean isFullDate(String strValue) {
if (strValue == null || strValue.trim().equals("")) {
return false;
}
try {
Tools.FULL_DATE_FORMAT.parse(strValue);
return true;
} catch (Exception ex) {
return false;
}
}
/** 字符串转日期型,不抛出异常,出错返回指定的缺省值 */
public static Date str2date(String strValue, Date theDefault) {
if (strValue == null)
return theDefault;
Date theDate;
SimpleDateFormat theFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
theDate = theFormat.parse(strValue);
} catch (ParseException ex) {
theDate = theDefault;
}
return theDate;
}
/** 字符串转日期型,抛出异常 */
public static Date str2dateEx(String strValue) throws ParseException {
if (strValue == null)
throw new ParseException("字符串为空", 0);
Date theDate;
SimpleDateFormat theFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
theDate = theFormat.parse(strValue);
return theDate;
}
/** 日期转字符串,采用“yyyy-MM-dd HH:mm:ss”的表示形式 */
public static String date2str(Date aDate) {
if (aDate == null)
return "";
SimpleDateFormat theFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return theFormat.format(aDate);
}
/** 日期转字符串,采用“yyyy-MM-dd”的表示形式 */
public static String getShortDate(Date nDate) {
if (nDate == null)
return "";
return FULL_YMD_FORMAT.format(nDate);
}
/** 日期转字符串,采用“yyyy-MM-dd HH:mm”的表示形式 */
public static String date2strShort(Date aDate) {
if (aDate == null)
return "";
SimpleDateFormat theFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
return theFormat.format(aDate);
}
/** 如果字符串为null,则返回空字符串,否则返回其本身 */
public static String blankNull(String str) {
if (str == null)
return "";
return str;
}
/** 如果字符串为null,则返回缺省字符串,否则返回其本身 */
public static String blankNull(String str, String strDefault) {
if (str == null)
return strDefault;
return str;
}
/** 如果字符串为null,则返回空字符串,否则返回其本身 */
public static String strNull(String str) {
if (str == null)
return "";
return str;
}
public static String strNullUl(String str) {
if (str == null || str.equals(""))
return "_";
return str;
}
/** 如果字符串为null或空字串,则返回6个空格,否则返回其本身 */
public static String strNullEx(String str) {
if (str == null || str.equals("") || str.equals("_"))
return copy(" ", 2);
if (str.equals("__"))
return "_";
return str;
}
/** 如果字符串为null或空串,则返回指定数量的空格,否则返回其本身 */
public static String strNullEx(String str, int count) {
if (str == null || str.equals("") || str.equals("_"))
return copy(" ", count);
if (str.equals("__"))
return "_";
return str;
}
public static String copy(String str, int count) {
StringBuffer sbf = new StringBuffer("");
if (count >= 0) {
for (int i = 1; i <= count; i++) {
sbf.append(str);
}
}
return sbf.toString();
}
/** 如果字符串为null,则返回缺省字符串,否则返回其本身 */
public static String strNull(String str, String strDefault) {
if (str == null)
return strDefault;
return str;
}
/** 如果字符串为null或空串,则返回缺省字符串,否则返回其本身 */
public static String strNullEx(String str, String strDefault) {
if (str == null || str.equals("") || str.equals("_"))
return strDefault;
if (str.equals("__"))
return "_";
return str;
}
/** 整数转字符串 */
public static String int2str(int intValue) {
return String.valueOf(intValue);
}
/** 整数转字符串 */
public static String int2str(double intValue) {
return String.valueOf(intValue);
}
/** 判断字符串是否为空,是则返回true */
public static boolean isNull(String strValue) {
if (strValue == null)
return true;
else
return false;
}
/** 判断字符串数组是否为空,是则返回true */
public static boolean isNull(String[] strValue) {
if (strValue == null)
return true;
else
return false;
}
// *判断字符串是否是整数 */
public static boolean isInt(String strValue) {
double nValue;
try {
nValue = Double.parseDouble(strValue);
if ((nValue - Integer.parseInt(strValue)) != 0) {
return false;
} else {
return true;
}
} catch (NumberFormatException e) {
return false;
}
// return true;
}
public static boolean isInt(double nValue) {
if (nValue - (new Double(nValue)).intValue() == 0) {
return true;
} else {
return false;
}
}
public static boolean isDouble(double nValue) {
if (nValue - (new Double(nValue)).intValue() != 0) {
return true;
} else {
return false;
}
}
// *判断字符串是否是double */
public static boolean isDouble(String strValue) {
double nValue;
try {
nValue = Double.parseDouble(strValue);
if ((nValue - Integer.parseInt(strValue)) != 0) {
return true;
} else {
return false;
}
} catch (NumberFormatException e) {
return false;
}
// return true;
}
/**
* 判断字符串是否是数值
* @param strValue
* @return
*/
public static boolean isNumber(String strValue) {
int nValue;
double nValue2;
boolean isInt;
boolean isDouble;
try {
nValue = Integer.parseInt(strValue);
isInt = true;
} catch (NumberFormatException e) {
isInt = false;
}
try {
nValue2 = Double.parseDouble(strValue);
isDouble = true;
} catch (NumberFormatException e) {
isDouble = false;
}
if (!isInt && !isDouble) {
return false;
}
return true;
}
public static String getWeek(Calendar theDate) {
if (theDate == null)
return "";
switch (theDate.get(Calendar.DAY_OF_WEEK)) {
case 1:
return "星期日";
case 2:
return "星期一";
case 3:
return "星期二";
case 4:
return "星期三";
case 5:
return "星期四";
case 6:
return "星期五";
case 7:
return "星期六";
default:
return "";
}
}
public static int getDateDiff(String sdate1, String sdate2, String fmt, TimeZone tz, int type) {
SimpleDateFormat df = new SimpleDateFormat(fmt);
Date date1 = null;
Date date2 = null;
try {
date1 = df.parse(sdate1);
date2 = df.parse(sdate2);
} catch (ParseException pe) {
pe.printStackTrace();
}
Calendar cal1 = null;
Calendar cal2 = null;
if (tz == null) {
cal1 = Calendar.getInstance();
cal2 = Calendar.getInstance();
} else {
cal1 = Calendar.getInstance(tz);
cal2 = Calendar.getInstance(tz);
}
// different date might have different offset
cal1.setTime(date1);
long ldate1 = date1.getTime() + cal1.get(Calendar.ZONE_OFFSET) + cal1.get(Calendar.DST_OFFSET);
cal2.setTime(date2);
long ldate2 = date2.getTime() + cal2.get(Calendar.ZONE_OFFSET) + cal2.get(Calendar.DST_OFFSET);
// Use integer calculation, truncate the decimals
int hr1 = (int) (ldate1 / 3600000); // 60*60*1000
int hr2 = (int) (ldate2 / 3600000);
int days1 = (int) hr1 / 24;
int days2 = (int) hr2 / 24;
int hourDiff = hr2 - hr1;
int dateDiff = days2 - days1;
int weekOffset = (cal2.get(Calendar.DAY_OF_WEEK) - cal1.get(Calendar.DAY_OF_WEEK)) < 0 ? 1 : 0;
int weekDiff = dateDiff / 7 + weekOffset;
int yearDiff = cal2.get(Calendar.YEAR) - cal1.get(Calendar.YEAR);
int monthDiff = yearDiff * 12 + cal2.get(Calendar.MONTH) - cal1.get(Calendar.MONTH);
switch (type) {
case 1:
return dateDiff;
case 2:
return weekDiff;
case 3:
return monthDiff;
case 4:
return yearDiff;
case 5:
return hourDiff;
default:
return 0;
}
}
public static long getLong(String theValue) {
int nPos = theValue.indexOf('.');
long lValue;
if (nPos == -1) {
lValue = Long.parseLong(theValue);
lValue *= 100;
} else {
String strInt;
if (nPos != 0)
strInt = theValue.substring(0, nPos);
else
strInt = "0";
nPos += 1;
int nLen = theValue.length();
int nXS;
if (nLen - nPos > 2) {
nXS = Integer.parseInt(theValue.substring(nPos, nPos + 2));
} else if (nLen == nPos)
nXS = 0;
else {
nXS = Integer.parseInt(theValue.substring(nPos));
}
if (nXS > 0 && nXS < 10 && !theValue.substring(nPos, nPos + 1).equals("0"))
nXS *= 10;
lValue = Long.parseLong(strInt) * 100;
lValue += nXS;
}
// System.out.println("lValue=" + lValue);
return lValue;
}
public static String getToday() {
Date theDate = new Date();
return CHINESE_DATE_FORMAT.format(theDate);
}
/* 按指定小数位数返回字符串类型的浮点数 */
public static String format(double col_value, int precision) {
if (precision >= 0) {
DecimalFormat dataFormat = new DecimalFormat("0" + (precision == 0 ? "" : ".") + copy("0", precision));
String value_str_final = dataFormat.format(col_value);
return (value_str_final);
} else {
if (Tools.isInt(col_value)) {
DecimalFormat dataFormat = new DecimalFormat("0");
String value_str_final = dataFormat.format(col_value);
return (value_str_final);
} else {
DecimalFormat dataFormat = new DecimalFormat("0." + copy("0", Math.abs(precision)));
String value_str_final = dataFormat.format(col_value);
return (value_str_final);
}
}
}
/** 将字符串数组用指定的分隔符组合成一个字符串 */
public static String combineStr(String[] strValue, String splitStr) {
if (strValue != null && splitStr != null && !splitStr.equals("")) {
StringBuffer str = new StringBuffer("");
for (int i = 0; i < strValue.length; i++) {
if (strValue[i] != null && !strValue[i].equals("")) {
if (i > 0)
str.append(splitStr); // 加入分隔符
str.append(strValue[i]);
}
}
return str.toString();
} else {
return ("");
}
}
/** 将字符串数组用默认的#分隔符组合成一个字符串,不存入空字符串 */
public static String combineStr(String[] strValue) {
String splitStr = "#";
if (strValue != null && splitStr != null && !splitStr.equals("")) {
StringBuffer str = new StringBuffer("");
for (int i = 0; i < strValue.length; i++) {
if (!strValue[i].equals("")) {
if (strValue[i] != null && !strValue[i].equals("")) {
if (i > 0)
str.append(splitStr); // 加入分隔符
str.append(strValue[i]);
}
}
}
return str.toString();
} else {
return ("");
}
}
/** 将int数组用默认的#分隔符组合成一个字符串,不存入空字符串 */
public static String combineInt(int[] intArr) {
String splitStr = "#";
if (intArr != null && splitStr != null && !splitStr.equals("")) {
StringBuffer str = new StringBuffer("");
for (int i = 0; i < intArr.length; i++) {
if (i > 0)
str.append(splitStr); // 加入分隔符
str.append(intArr[i]);
}
return str.toString();
} else {
return ("");
}
}
public static String combineInt(int[] intArr, String splitStr) {
if (intArr != null && splitStr != null && !splitStr.equals("")) {
StringBuffer str = new StringBuffer("");
for (int i = 0; i < intArr.length; i++) {
if (i > 0)
str.append(splitStr); // 加入分隔符
str.append(intArr[i]);
}
return str.toString();
} else {
return ("");
}
}
/** 将字符串数组用默认的#分隔符组合成一个字符串,空字符串用_替换 */
public static String combineStrEx(String[] strValue) {
String splitStr = "#";
if (strValue != null && splitStr != null && !splitStr.equals("")) {
StringBuffer str = new StringBuffer("");
for (int i = 0; i < strValue.length; i++) {
if (i > 0)
str.append(splitStr); // 加入分隔符
if (strValue[i] == null || strValue[i].equals("")) {
str.append("_");
} else {
str.append(strValue[i]);
}
}
return str.toString();
} else {
return ("");
}
}
/** 将字符串数组用指定的分隔符组合成一个字符串,空字符串用_替换 */
public static String combineStrEx(String[] strValue, String splitStr) {
if (strValue != null && splitStr != null && !splitStr.equals("")) {
StringBuffer str = new StringBuffer("");
for (int i = 0; i < strValue.length; i++) {
if (i > 0)
str.append(splitStr); // 加入分隔符
if (strValue[i] == null || strValue[i].equals("")) {
str.append("_");
} else {
str.append(strValue[i]);
}
}
return str.toString();
} else {
return ("");
}
}
/** 将一个字符串按指定分隔符分成一个字符串数组 */
public static String[] splitStr(String strValue, String splitStr) {
if (strValue != null && splitStr != null) {
Vector vc = new Vector();
StringTokenizer strToken = new StringTokenizer(strValue, splitStr);
while (strToken.hasMoreTokens()) {
vc.add(strToken.nextToken());
}
int size = vc.size();
String[] returnStr = new String[size];
for (int j = 0; j < size; j++) {
returnStr[j] = (String) vc.get(j);
}
return returnStr;
} else {
return (new String[] {});
}
}
/** 将一个字符串按默认的#分隔符分成一个字符串数组 */
public static String[] splitStr(String strValue) {
if (strValue != null) {
Vector vc = new Vector();
String splitStr = "#";
StringTokenizer strToken = new StringTokenizer(strValue, splitStr);
while (strToken.hasMoreTokens()) {
vc.add(strToken.nextToken());
}
int size = vc.size();
String[] returnStr = new String[size];
for (int j = 0; j < size; j++) {
returnStr[j] = (String) vc.get(j);
}
return returnStr;
} else {
return (new String[] {});
}
}
/** 将一个字符串按默认的#分隔符分成一个字符串数组,_转换成空 */
public static String[] splitStrEx(String strValue) {
if (strValue != null) {
Vector vc = new Vector();
String splitStr = "#";
StringTokenizer strToken = new StringTokenizer(strValue, splitStr);
while (strToken.hasMoreTokens()) {
vc.add(strToken.nextToken());
}
int size = vc.size();
String[] returnStr = new String[size];
for (int j = 0; j < size; j++) {
if (((String) vc.get(j)).equals("_")) {
returnStr[j] = "";
} else {
if (((String) vc.get(j)).equals("__")) {
returnStr[j] = "_";
} else {
returnStr[j] = (String) vc.get(j);
}
}
}
return returnStr;
} else {
return (new String[] {});
}
}
/** 将一个字符串按指定的分隔符分成一个字符串数组,_转换成空字符串 */
public static String[] splitStrEx(String strValue, String splitStr) {
if (strValue != null) {
Vector vc = new Vector();
StringTokenizer strToken = new StringTokenizer(strValue, splitStr);
while (strToken.hasMoreTokens()) {
vc.add(strToken.nextToken());
}
int size = vc.size();
String[] returnStr = new String[size];
for (int j = 0; j < size; j++) {
if (((String) vc.get(j)).equals("_")) {
returnStr[j] = "";
} else {
if (((String) vc.get(j)).equals("__")) {
returnStr[j] = "_";
} else {
returnStr[j] = (String) vc.get(j);
}
}
}
return returnStr;
} else {
return (new String[] {});
}
}
/** 查找指定字符串数组中是否包含指定字符串 */
public static boolean contain(String[] strValue, String strToCheck) {
if (strValue != null) {
for (int i = 0; i < strValue.length; i++) {
if (strValue[i].equals(strToCheck))
return true;
}
}
return false;
}
/** 取得指定字符的下一个字符 */
public static String nextChar(String orgChar) {
char ch;
if (orgChar != null && !orgChar.equals("")) {
ch = orgChar.charAt(0);
return String.valueOf(++ch);
} else {
return "";
}
}
/** 将整型数组转换成字符串数组 */
public static String[] intArrToStrArr(int[] intArr) {
String[] theStr = new String[intArr.length];
for (int i = 0; i < intArr.length; i++) {
theStr[i] = int2str(intArr[i]);
}
return theStr;
}
/** 将字符串数组转换成整型数组 */
public static int[] strArrToIntArr(String[] strArr) {
int[] theInt = new int[strArr.length];
for (int i = 0; i < strArr.length; i++) {
theInt[i] = str2intOld(strArr[i]);
}
return theInt;
}
/** 判断orgStr是否全由desChar组成 */
public static boolean isAll(String orgStr, char desChar) {
for (int i = 0; i < orgStr.length(); i++) {
if (orgStr.charAt(i) == desChar) {
continue;
} else {
return false;
}
}
return true;
}
/** 字符串替换方法,将字符串 strSource 中的子字符串 strFrom 替换成 strTo */
public static String replace(String strSource, String strFrom, String strTo) {
if (strSource != null) {
if (strFrom != null && strTo != null) {
String strDest = "";
int intFromLen = strFrom.length();
int intPos;
while ((intPos = strSource.indexOf(strFrom)) != -1) {
strDest = strDest + strSource.substring(0, intPos);
strDest = strDest + strTo;
strSource = strSource.substring(intPos + intFromLen);
}
strDest = strDest + strSource;
return strDest;
} else {
return strSource;
}
} else {
return strSource;
}
}
/** 将 strSource 中的单引号替换成两个单引号 */
public static String replaceQuto(String strSource) {
if (strSource != null) {
strSource = replace(strSource, "'", "''");
}
return strSource;
}
/** 将字符串中的特殊子字符串替换成 replaceStr 中指定的值 */
public static String htmlEncode(String strSource) {
if (strSource != null) {
int i = 0;
while (i < replaceStr.length) {
if ((i + 1) < replaceStr.length) {
strSource = replace(strSource, replaceStr[i], replaceStr[i + 1]);
i = i + 2;
}
}
}
return strSource;
}
/**
* 取最右边若干字符. 如果字符串长度小于指定的长度,则返回整个字符串.
*
* @param str:
* 需要截取的字符串
* @param nRigth:
* 指定最右边的位数
*/
public static String right(String str, int nRight) {
if (str == null)
return null;
int nLen = str.length();
int nStart = nLen > nRight ? nLen - nRight : 0;
return str.substring(nStart, nStart + nRight);
}
/**
* 返回从指定位置开始的,第一次出现指定字符数组中任一个字符的位置. 相当于对 指定字符数组中的所有字符做一次indexOf后,取其中最小的位置. 对于指定位置, 这里没有任何限制。如果指定位置<0,则相当于0,表示搜索整个字符串;如果指
* 定位置大于字符串的长度,则返回-1。如果指定字符数组为空,也返回-1。
*
* @param str:String
* 被搜索的字符串。
* @param aChars:
* char[] 包含指定字符的数组。
* @param nBeginIndex:开始搜索的起始位置。
* @return 返回第一次出现指定字符数组中任一字符的位置;如果从指定的起始位置 开始没有出现任何指定的字符,或者起始位置超出范围,或者没有指定任何字符, 则返回-1。
*/
public static int indexOfChars(String str, char[] aChars, int nBeginIndex) {
if (nBeginIndex < 0)
nBeginIndex = 0;
if (aChars == null || aChars.length == 0 || str == null || str.length() <= nBeginIndex) {
return -1;
}
int nMin = -1;
int nIndex = -1;
for (int i = 0; i < aChars.length; i++) {
nIndex = str.indexOf(aChars[i], nBeginIndex);
if (nIndex == nBeginIndex) {
return nIndex;
}
if (nIndex != -1) {
if (nMin == -1)
nMin = nIndex;
else if (nIndex < nMin)
nMin = nIndex;
}
}
return nMin;
}
/** 获得本机IP */
public static String getLocalIP() {
try {
String ip = InetAddress.getLocalHost().toString();
ip = ip.substring(ip.indexOf("/") + 1);
return ip;
} catch (UnknownHostException e) {
return "未知IP";
}
}
public static String getFormContent(InputStream requestForm, ByteArrayOutputStream baos) {
String buff = new String();
try {
byte[] ba = new byte[1024];
int read = 0;
while ((read = requestForm.read(ba)) != -1) {
baos.write(ba, 0, read);
}
if (baos != null) {
buff = new String(baos.toByteArray());
}
baos.close();
} catch (IOException e) {
}
return buff;
}
public static String getFormContent(InputStream requestForm) {
String buff = new String();
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] ba = new byte[1024];
int read = 0;
while ((read = requestForm.read(ba)) != -1) {
baos.write(ba, 0, read);
}
if (baos != null) {
buff = new String(baos.toByteArray());
}
baos.close();
} catch (IOException e) {
}
return buff;
}
public static String getUTF8Content(InputStream requestForm) {
String buff = new String();
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] ba = new byte[1024];
int read = 0;
while ((read = requestForm.read(ba)) != -1) {
baos.write(ba, 0, read);
}
if (baos != null) {
buff = new String(baos.toByteArray(),"UTF-8");
}
baos.close();
} catch (IOException e) {
}
return buff;
}
public static String getGBKContent(InputStream requestForm,ByteArrayOutputStream baos) {
String buff = new String();
try {
byte[] ba = new byte[1024];
int read = 0;
while ((read = requestForm.read(ba)) != -1) {
baos.write(ba, 0, read);
}
if (baos != null) {
buff = new String(baos.toByteArray(),"GBK");
}
baos.close();
} catch (IOException e) {
}
return buff;
}
public static String getGBKContent(InputStream requestForm) {
String buff = new String();
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] ba = new byte[1024];
int read = 0;
while ((read = requestForm.read(ba)) != -1) {
baos.write(ba, 0, read);
}
if (baos != null) {
buff = new String(baos.toByteArray(),"GBK");
}
baos.close();
} catch (IOException e) {
}
return buff;
}
/**
* 根据身份证号码获得生日
*
* @param certID
* 身份证号
* @return 生日的Calendar值
*/
public static Calendar getBirthdayFromCertID(final String certID) {
Calendar birth = Calendar.getInstance();
String sBirth = null;
SimpleDateFormat sdf = null;
if (certID.length() == 15) {
sBirth = certID.substring(6, 12);
sdf = new SimpleDateFormat("yyMMdd");
} else if (certID.length() == 18) {
sBirth = certID.substring(6, 14);
sdf = new SimpleDateFormat("yyyyMMdd");
}
if (sBirth != null) {
try {
java.util.Date d = sdf.parse(sBirth);
birth.setTime(d);
} catch (ParseException e) {
}
}
return birth;
}
/**
* 参考定义的正则表达式
*
* @param str
* @return
*/
public static boolean isNum(String str) {
if (str == null)
return false;
Matcher is = numPattern.matcher(str);
if (is.matches()) {
return true;
} else {
return false;
}
}
/**
* 参考定义的正则表达式
*
* @param str
* @return
*/
public static boolean isNumLetter(String str) {
if (str == null)
return false;
Matcher is = numLetterPattern.matcher(str);
if (is.matches()) {
return true;
} else {
return false;
}
}
/**
* 参考定义的正则表达式
*
* @param str
* @return
*/
public static boolean isHex(String str) {
if (str == null)
return false;
Matcher is = hexPattern.matcher(str);
if (is.matches()) {
return true;
} else {
return false;
}
}
/**
* @param str
* @return 假如有异常,则return -1
*/
public static int str2int(String str) {
return str2int(str, -1);
}
/**
* @param str
* @param
* @return
*/
public static int str2int(String str, int i) {
if (str == null ||"".equals(str.trim()))
return i;
int ret = -2;
try {
ret = Integer.parseInt(str.trim());
} catch (Exception e) {
// do nothing
}
return ret;
}
/**
* 根据keyword中的每个单词,从content中取出包含单词的summary
*
* @param string
* @param keyword
* @return
* @throws ParseException
*/
public static String getSummary(String content, String keyword) {
StringBuffer ret = new StringBuffer();
HashSet set = new HashSet();
String[] ca = sentencePattern.split(content);
String[] ka = keyword.split(" ");
for (int i = 0; i < ka.length; ++i) {
String kw = ka[i].trim();
ka[i] = "";
int len = kw.length();
kw = kw.substring(kw.indexOf(":") + 1, len);
len = kw.length();
for (int j = 0; j < ca.length; ++j) {
String str = ca[j];
if (str.length() < len)
continue;
if ("".equals(ka[i]) && str.indexOf(kw) != -1) {
ka[i] = str;
set.add(str);
}
}
}
Iterator it = set.iterator();
while (it.hasNext()) {
ret.append(it.next());
ret.append(" ... ");
}
return ret.toString();
}
/**
* @param url
* @return
*/
public static String getSite(String url) {
String ret = "";
try {
URI uri = new URI("http://" + url);
ret = uri.getHost();
} catch (URISyntaxException e) {
e.printStackTrace();
}
return ret;
}
/**
* 得到开始月份和结束月份间所有的后缀(eg. 2006_7),时区为 GMT+8
*
* @param startTm
* @param endTm
* @return 后缀的列表,从小到大排序
*/
public static List getAllPostFix(long startTm, long endTm) {
List ret = new ArrayList();
if (startTm > endTm)
return ret;
Calendar startCal = new GregorianCalendar(TimeZone.getTimeZone("GMT+8"));
startCal.setTimeInMillis(startTm);
startCal.set(Calendar.DAY_OF_MONTH, 1);
Calendar endCal = new GregorianCalendar(TimeZone.getTimeZone("GMT+8"));
endCal.setTimeInMillis(endTm);
endCal.set(Calendar.DAY_OF_MONTH, 2);
for (; startCal.before(endCal); startCal.add(Calendar.MONTH, 1)) {
String s = startCal.get(Calendar.YEAR) + "_" + (startCal.get(Calendar.MONTH) + 1);
ret.add(s);
}
return ret;
}
/**
* 将指定byte数组以16进制的形式打印到控制台
*
* @param hint
* String
* @param b
* byte[]
* @return void
*/
public static void printHexString(String hint, byte[] b) {
for (int i = 0; i < b.length; i++) {
String hex = Integer.toHexString(b[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
}
}
/**
*
* @param b
* byte[]
* @return String
*/
public static String bytes2HexString(byte[] b, int len) {
String ret = "";
for (int i = 0; i < len; i++) {
String hex = Integer.toHexString(b[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
ret += hex.toUpperCase();
}
return ret;
}
/**
* 将两个ASCII字符合成一个字节; 如:EF--> 0xEF
*
* @param src0
* byte
* @param src1
* byte
* @return byte
*/
public static byte uniteBytes(byte src0, byte src1) {
byte _b0 = Byte.decode("0x" + new String(new byte[] { src0 })).byteValue();
_b0 = (byte) (_b0 << 4);
byte _b1 = Byte.decode("0x" + new String(new byte[] { src1 })).byteValue();
byte ret = (byte) (_b0 ^ _b1);
return ret;
}
/**
* 将指定字符串src,以每两个字符分割转换为16进制形式 如:2B44EFD9 --> byte[]{0x2B, 0x44, 0xEF, 0xD9}
*
* @param src
* String
* @return byte[]
*/
public static byte[] hexString2Bytes(String src) {
int len = src.length();
byte[] ret = new byte[len / 2];
byte[] tmp = src.getBytes();
for (int i = 0; i < ret.length; i++) {
ret[i] = uniteBytes(tmp[i * 2], tmp[i * 2 + 1]);
}
return ret;
}
public static String transformCharset(String str, String charsetNameFrom, String charsetNameTo) {
String ret = str;
try {
ret = new String(str.getBytes(charsetNameFrom), charsetNameTo);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return ret;
}
/**
* 把 delimiter 分隔的数组,变成数组List
*
* @param ba
* @param delimiter
* @return
*/
public static List getList4ByteArray(byte[] ba, int delimiter) {
List ret = new ArrayList();
int begin = 0, len = 0;
for (int i = 0; i < ba.length; ++i) {
if (ba[i] == delimiter || i == (ba.length - 1)) {
len = i - begin;
// 处理最后那个
if (i == (ba.length - 1) && ba[i] != delimiter)
++len;
byte[] temp = new byte[len];
System.arraycopy(ba, begin, temp, 0, len);
ret.add(temp);
begin = i + 1;// 1--去掉那个delimiter,即假设delimiter占一个byte
}
}
return ret;
}
/**
* 判断是否为UTF-8的URL编码
*
* @param text
* @return
* @author Jeremy Ye
*/
public static boolean isUTF8URL(String text) {
text = text.toLowerCase();
int p = text.indexOf("%");
if (p != -1 && text.length() - p > 9) {
text = text.substring(p, p + 9);
}
return UTF8CodeCheck(text);
}
/**
* 判断编码是否为UTF-8的编码
*
* @param text
* @return
* @author Jeremy Ye
*/
private static boolean UTF8CodeCheck(String text) {
String sign = "";
if (text.startsWith("%e")) {
for (int i = 0, p = 0; p != -1; i++) {
p = text.indexOf("%", p);
if (p != -1)
p++;
sign += p;
}
}
return sign.equals("147-1");
}
/**
* Utf8URL解码
*
* @param text
* @return
* @author Jeremy Ye
*/
public static String UTF8URLdecode(String text) {
String result = "";
int p = 0;
if (text != null && text.length() > 0) {
text = text.toLowerCase();
p = text.indexOf("%e");
if (p == -1) {
return text;
}
while (p != -1) {
result += text.substring(0, p);
text = text.substring(p, text.length());
if (text == "" || text.length() < 9) {
return result;
}
result += Code2Word(text.substring(0, 9));
text = text.substring(9, text.length());
p = text.indexOf("%e");
}
}
return result + text;
}
/**
* UTF-8的URL编码转字符
*
* @param text
* @return
* @author Jeremy Ye
*/
private static String Code2Word(String text) {
String result;
if (UTF8CodeCheck(text)) {
byte[] code = new byte[3];
code[0] = (byte) (Integer.parseInt(text.substring(1, 3), 16) - 256);
code[1] = (byte) (Integer.parseInt(text.substring(4, 6), 16) - 256);
code[2] = (byte) (Integer.parseInt(text.substring(7, 9), 16) - 256);
try {
result = new String(code, "UTF-8");
} catch (UnsupportedEncodingException ex) {
result = null;
}
} else {
result = text;
}
return result;
}
/**
* 将文件打成zip包
*
* @param inputFileName
* @throws Exception
*/
public static void zip(String inputFileName, String zipFileName) throws Exception {
// String zipFileName = "c:\\pic.zip";
zip(zipFileName, new File(inputFileName));
}
public static void zip(String zipFileName, File inputFile) throws Exception {
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));
zip(out, inputFile, "");
out.close();
}
private static void zip(ZipOutputStream out, File f, String base) throws Exception {
if (f.isDirectory()) {
File[] f1 = f.listFiles();
out.putNextEntry(new ZipEntry(base + "/"));
base = base.length() == 0 ? "" : base + "/";
for (int i = 0; i < f1.length; i++)
zip(out, f1[i], base + f1[i].getName());
} else {
out.putNextEntry(new ZipEntry(base));
FileInputStream in = new FileInputStream(f);
int i = 0;
byte b[]=new byte[1024];
// System.out.println("zip:" + f.getName());
while ((i = in.read(b)) != -1)
out.write(b, 0, i);
in.close();
}
}
/**
* 把byte流串转换为zip
*
* @param data
* @param fileName
* @return
*/
public static byte[] trun2Zip(byte[] data, String fileName) {
ByteArrayOutputStream zipBuffer = null;
try {
zipBuffer = new ByteArrayOutputStream();
ZipOutputStream zip = new ZipOutputStream(zipBuffer);
zip.putNextEntry(new ZipEntry(fileName));
zip.write(data);
zip.flush();
zip.closeEntry();
zip.close();
return zipBuffer.toByteArray();
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
try {
zipBuffer.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
/**
* 通过身份证号码获取性别
*
* @param certID
* 身份证号码
* @return 性别 男=0 女=1
*/
public static int getSexFromCertID(final String certID) {
int sex = 0;
if (certID.length() == 15) {
sex = certID.charAt(14) - 30;
} else if (certID.length() == 18) {
sex = certID.charAt(16) - 30;
}
return (sex % 2 == 0 ? 1 : 0);
}
/* ================== 以上定义公有属性和方法 ================== */
/* ================== 以下定义私有属性和方法 ================== */
private final static Date the1stDay = new Date(0);
private final static SimpleDateFormat CHINESE_DATE_FORMAT = new SimpleDateFormat("yyyy年MM月dd日");
/** 特殊字符替换的对应关系 */
private final static String replaceStr[] = { "<", "<", "/>", "/>", "\r\n", "<br>", " ", " " };
private Tools() {
}
/* ================== 以上定义私有属性和方法 ================== */
/**
* 删除指定文件夹啊所有文件 path 文件夹完整绝对路径
*/
public static boolean delAllFile(String filePath) {
boolean flag = false;
File file = new File(filePath);
if (!file.exists()) {
return flag;
}
if (!file.isDirectory()) {
return flag;
}
String[] tempList = file.list();
File temp = null;
for (int i = 0; i < tempList.length; i++) {
if (filePath.endsWith(File.separator)) {
temp = new File(filePath + tempList[i]);
} else {
temp = new File(filePath + File.separator + tempList[i]);
}
if (temp.isFile()) {
temp.delete();
}
if (temp.isDirectory()) {
delAllFile(filePath + "/" + tempList[i]);
flag = true;
}
}
return flag;
}
/**
* 删除指定文件夹啊所有文件 path 文件夹完整绝对路径
*/
public static void delFolder(String folderPath) {
try {
delAllFile(folderPath);
String filePath = folderPath;
filePath = filePath.toString();
File myFilePath = new File(filePath);
myFilePath.delete();
} catch (Exception e) {
// TODO: handle exception
}
}
/**
* 中文转拼音
*
* @param chinese
* @return
*/
public static String chineseFormatPinyin(String chinese) {
StringBuffer buffer = new StringBuffer();
String[] t2 = new String[100];
HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
// format.setCaseType(HanyuPinyinCaseType.UPPERCASE);
format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
format.setVCharType(HanyuPinyinVCharType.WITH_V);
try {
for (int i = 0; i < chinese.length(); i++) {
char k = chinese.charAt(i);
if (k != ' ') {
if (Character.toString(k).matches("[\\u4E00-\\u9FA5]+")) {
t2 = PinyinHelper.toHanyuPinyinStringArray(k, format);
buffer.append(t2[0]);
} else {
buffer.append(k);
}
} else {
buffer.append(" ");
}
}
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
return buffer.toString();
}
public static void delAllFolder(String folderPath) {
File folder = new File(folderPath);
File[] files = folder.listFiles();
if (files != null) {
if (files.length == 0) {
folder.delete();
} else {
for (int k = 0; k < files.length; k++) {
String picPath = folderPath + files[k].getName() + File.separator;
delAllFolder(picPath);
if (files != null) {
folder.delete();
}
if (files.length == 0) {
folder.delete();
}
}
}
} else {
folder.delete();
}
}
public static void sendHttpUrl(InputStream is,String parameter,String servletName){
PostMethod httppost = null;
HttpClient httpclient = new HttpClient();
try{
String url = "http://" + GlobalKeys.getPolicePropertyByKey("url.target.ip")+ servletName;
httppost = new PostMethod(url);
httpclient.getParams().setConnectionManagerTimeout(5000);
httpclient.getParams().setSoTimeout(5000);
httppost.setRequestBody(is);
httppost.setQueryString(parameter);
httpclient.executeMethod(httppost);
} catch(ConnectException e){
System.out.println("sendHttpUrl connect error");
} catch(Exception ex){
ex.printStackTrace();
}finally{
if(is!=null){
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
httppost.releaseConnection();
httpclient.getHttpConnectionManager().closeIdleConnections(0);
}
}
/**
* 发送给接收中心基础命令
*
* @return true:成功;false:失败
*/
public static boolean sendToConnectReceCenter(String refreshType,String freshType) {
PostMethod httpMethod = null;
HttpClient httpclient = new HttpClient();
try {
String urlAddress = GlobalKeys.getPolicePropertyByKey("rececenter_url") + "/servlet/RefreshCacheServlet"; // police.properties
String params = "?module="+refreshType+"&freshType="+freshType;
String url = urlAddress + params;
httpMethod = new PostMethod(url);
httpclient.executeMethod(httpMethod);
} catch (Exception ex) {
return false;
} finally {
httpMethod.releaseConnection();
httpclient.getHttpConnectionManager().closeIdleConnections(0);
}
return true;
}
public static int getCertIDYear(String certID){
try{
String year = null;
if(StringUtils.isEmpty(certID)){
return 0;
}
if (certID.length() == 15) {
year = certID.substring(6, 8);
} else if (certID.length() == 18) {
year = certID.substring(6, 10);
}
if (year != null&&isNum(year)) {
return Integer.parseInt(year);
}
} catch (Exception e){
System.err.println(certID + " get year error!");
}
return 0;
}
/**
* 查找文件的扩展名,返回格式(如: .txt;.png等)
* @param fileName
* @return
*/
public static String getFileType(String fileName){
Matcher m = fileTypePattern.matcher(fileName);
if(m.find()){
return m.group();
} else {
return "";
}
}
/**
* 手机号码正则限制
* @param mobiles
* @return
*/
public static boolean isMobileNO(String mobiles){
if(mobiles == null){
return false;
}
Pattern p = Pattern.compile("^1[3|4|5|8][0-9]\\d{8}$");
Matcher m = p.matcher(mobiles.trim());
return m.matches();
}
/**
* 字符串是否为空
* @param stringValue
* @return
*/
public static boolean isEmptyString(String stringValue) {
if (stringValue == null || stringValue.trim().length() < 1 || stringValue.trim().equalsIgnoreCase("null")) {
return true;
} else {
return false;
}
}
/**
* 字符串是否不为空
* @param stringValue
* @return
*/
public static boolean isNotEmptyString(String stringValue) {
return !isEmptyString(stringValue);
}
}