/**
*自己整理的String工具类,小部分自己写的,大部分公司同事写的,
*转载请务必载明出处: https://mp.csdn.net/mdeditor/102723933#
*/
package com.hqblicai.base.util;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import org.apache.log4j.Logger;
public class DateUtils {
private static Logger logger = Logger.getLogger(DateUtils.class);
/*
* yyyy-MM-dd HH:mm:ss
*/
public static final String LONG_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
/*
* yyyy-MM-dd
*/
public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
/**
*
* 功能描述:获取前一天 yyyy-MM-dd
* @author: guozi
* @param:
* @date: 2018年10月19日 上午10:53:00
*/
public static String getFrontTime(Date date){
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, -1);
date = calendar.getTime();
return sdf.format(date);
}
/**
*
* 功能描述:获取前几月或者后几月,`注意月份`
* @author: guozi
* @param:
* @date: 2018年10月19日 上午10:53:00
*/
public static Date getDateBeforeOrAfter(Date curDate, int iDate) {
Calendar cal = Calendar.getInstance();
if (curDate != null) {
cal.setTime(curDate);
}
cal.add(Calendar.DAY_OF_MONTH, iDate);
return cal.getTime();
}
/**
* 凌晨
*
* @param date
* @flag 0 返回yyyy-MM-dd 00:00:00日期<br>
* 1 返回yyyy-MM-dd 23:59:59日期
* @return
*/
public static Date getMinOrMaxDate(Date date, boolean isMinTime) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
if (isMinTime) {
return cal.getTime();
} else {
cal.add(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.MILLISECOND, -999);
}
return cal.getTime();
}
/**
* 将日期转换成指定格式的字符串
* @param date - 要转换的日期
* @param dateFormat - 日期格式
* @return String 日期对应的字符串
*/
public static String convertDate2String(Date date, String dateFormat) {
SimpleDateFormat sdf = null;
if(dateFormat != null && !dateFormat.equals("")) {
sdf = new SimpleDateFormat(dateFormat);
} else {
sdf = new SimpleDateFormat(LONG_DATE_FORMAT);
}
return sdf.format(date);
}
/**
*
* 功能描述:将时间`date`类型转换为`String`类型,其中
* new SimpleDateFormat("yyyy-MM-dd");里面的格式可以自定义
* @author: guozi
* @param:
* @date: 2018年10月19日 上午10:53:00
*/
public static Date getDateYYYYMMdd(String str) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = format.parse(str);
} catch (ParseException e) {
logger.error(e.getMessage(), e);
}
return date;
}
/**
* 时间类型转为秒
* @param @param date
* @param @return
*/
public static String DateToTime(Date date){
if(date==null){
return "0";
}else{
return String.valueOf(date.getTime()/1000);
}
}
/**
* 日期比较
*
* @param DATE1
* @param DATE2
* @return
*/
public static boolean compare_date(Date DATE1, Date DATE2) {
try {
if (DATE1.getTime() > DATE2.getTime()) {
return true;
} else if (DATE1.getTime() < DATE2.getTime()) {
return false;
} else {
return false;
}
} catch (Exception exception) {
exception.printStackTrace();
}
return false;
}
/**
* 将时间字符串转化为时间
* example:2016-09-18 23:59:59
* @param d
* @return
*/
public static Date getDate(String str, String dateFormat) {
SimpleDateFormat format = new SimpleDateFormat(dateFormat);
Date date = null;
try {
date = format.parse(str);
} catch (ParseException e) {
logger.error(e.getMessage(), e);
}
return date;
}
/**
*
* @描述:得到几天后的时间
* @作者:guozi
* @创建时间: 2015-10-23
* @param @param
* d
* @param @param
* day
* @param @return
*/
public static Date getDateAfter(Date d, int day) {
Calendar now = Calendar.getInstance();
now.setTime(d);
now.set(Calendar.DATE, now.get(Calendar.DATE) + day);
return now.getTime();
}
/**
* date当天最后时间
* example:2016-09-18 23:59:59
* @param d
* @return
*/
public static Date getLastSecIntegralTime(Date d){
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(d.getTime());
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.SECOND, 59);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
/**
* date当天开始时间
* example:2016-09-18 00:00:00
* @param d
* @return
*/
public static Date getStartIntegralTime(Date d){
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(d.getTime());
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
/**
* 计算两个时间相差天数
* @param date1 <String>
* @param date2 <String>
* @return int
* @throws ParseException
*/
public static int getDaySpace(Date dbtime1 , Date dbtime2 ) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
int day = 0;
try {
Date date1 = sdf.parse(sdf.format(dbtime1));
Date date2 = sdf.parse(sdf.format(dbtime2));
day = (int) ((date2.getTime() - date1.getTime()) / (1000*3600*24));
} catch (ParseException e) {
logger.error("计算两个时间相差天数失败" + e.getMessage());
logger.error(e.getMessage(), e);
}
return day;
}
public static Date getNowTime() throws ParseException{
SimpleDateFormat sdf=new SimpleDateFormat(DEFAULT_DATE_FORMAT);
String str=sdf.format(new Date());
Date mydate = sdf.parse(str);
return mydate;
}
/**
*
* 功能描述:可以做成定时器,以分钟为单位
* @author: guozi
* @param:
* @date: 2018年10月19日 上午10:53:00
*/
public static Date getDateBeforeOrAfterMinute(Date curDate, int min) {
Calendar cal = Calendar.getInstance();
if (curDate != null) {
cal.setTime(curDate);
}
cal.add(Calendar.MINUTE, min);
return cal.getTime();
}
/**
* 正则表达式:验证手机号
*/
public static final String REGEX_MOBILE = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])| (19[8|9]))\\d{8}$";
/**
* 校验手机号
*
* @param mobile
* @return 校验通过返回true,否则返回false
*/
public static boolean isPhone(String mobile) {
return Pattern.matches(REGEX_MOBILE, mobile);
}
/**
* 如果是null,将其置为''
*/
public static String isNull(Object o) {
if (o == null) {
return "";
}
String str = "";
if (o instanceof String) {
str = (String) o;
} else {
str = o.toString();
}
return str;
}
public static boolean isBlank(String str){
return StringUtils.isNull(str).equals("");
}
/**
* 分割字符得到前后两个字符
*
* @param str
* @param separatorChar
* :分割符
* @return
*/
public static String[] splitFirstLast(String str, String separatorChar) {
String[] s = str.split(separatorChar);
String first = "";
String last = "";
if (s != null && s.length > 0) {
first = s[0];
if (s.length > 1) {
last = s[s.length - 1];
}
}
return new String[] { first, last };
}
/**
* 首字母转大写
*
* @param s
*/
public static String toUpperCaseFirstOne(String s) {
if (isEmpty(s))
return s;
if (Character.isUpperCase(s.charAt(0)))
return s;
else
return (new StringBuilder()).append(Character.toUpperCase(s.charAt(0))).append(s.substring(1)).toString();
}
/**
* 判断是不是一个合法的电子邮件地址
*
* @param email
* @return
*/
public static boolean isEmail(String email) {
if (email == null)
return false;
email = email.trim();
if (email.indexOf(' ') != -1)
return false;
int idx = email.indexOf('@');
if (idx == -1 || idx == 0 || (idx + 1) == email.length())
return false;
if (email.indexOf('@', idx + 1) != -1)
return false;
if (email.indexOf('.') == -1)
return false;
return true;
}
/**
* 除去字符串尾部的指定字符,如果字符串是null,依然返回null。
*
* @param str
* 要处理的字符串
* @param stripChars
* 要除去的字符,如果为null表示除去空白字符
* @return 除去指定字符后的的字符串,如果原字串为null,则返回null
*/
public static String trimEnd(String str, String stripChars) {
return trim(str, stripChars, 1);
}
/**
* 除去字符串头尾部的指定字符,如果字符串是null,依然返回null。
*
* @param str
* 要处理的字符串
* @param stripChars
* 要除去的字符,如果为null表示除去空白字符
* @param mode
* -1表示trimStart,0表示trim全部,1表示trimEnd
* @return 除去指定字符后的的字符串,如果原字串为null,则返回null
*/
public static String trim(String str, String stripChars, int mode) {
if (str == null) {
return null;
}
int length = str.length();
int start = 0;
int end = length;
if (mode <= 0) {
if (stripChars == null) {
while ((start < end) && (Character.isWhitespace(str.charAt(start)))) {
start++;
}
} else if (stripChars.length() == 0) {
return str;
} else {
while ((start < end) && (stripChars.indexOf(str.charAt(start)) != -1)) {
start++;
}
}
}
if (mode >= 0) {
if (stripChars == null) {
while ((start < end) && (Character.isWhitespace(str.charAt(end - 1)))) {
end--;
}
} else if (stripChars.length() == 0) {
return str;
} else {
while ((start < end) && (stripChars.indexOf(str.charAt(end - 1)) != -1)) {
end--;
}
}
}
if ((start > 0) || (end < length)) {
return str.substring(start, end);
}
return str;
}
/**
* 截取字符串,(如果字符串包含HTML标签,则先去除HTML后再进行截取)
*
* @autor:chenssy
* @date:2014年8月10日
*
* @param htmlString
* @param length
* @return
*/
public static String subHTMLString(String htmlString, int length) {
return subStringReplaceDot(delHTMLTag(htmlString), length);
}
/**
* 过滤html标签,包括script、style、html、空格、回车标签
*
* @autor:chenssy
* @date:2014年8月10日
*
* @param htmlStr
* @return
*/
public static String delHTMLTag(String htmlStr) {
String regEx_script = "<script[^>]*?>[\\s\\S]*?<\\/script>"; // 定义script的正则表达式
String regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>"; // 定义style的正则表达式
String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式
String regEx_space = "\\s*|\t|\r|\n";// 定义空格回车换行符
Pattern p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
Matcher m_script = p_script.matcher(htmlStr);
htmlStr = m_script.replaceAll(""); // 过滤script标签
Pattern p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
Matcher m_style = p_style.matcher(htmlStr);
htmlStr = m_style.replaceAll(""); // 过滤style标签
Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
Matcher m_html = p_html.matcher(htmlStr);
htmlStr = m_html.replaceAll(""); // 过滤html标签
Pattern p_space = Pattern.compile(regEx_space, Pattern.CASE_INSENSITIVE);
Matcher m_space = p_space.matcher(htmlStr);
htmlStr = m_space.replaceAll(""); // 过滤空格回车标签
return htmlStr.trim(); // 返回文本字符串
}
/**
* 将字符串转移为ASCII码
*
* @param cnStr
* @return
*/
public static String getCnASCII(String cnStr) {
StringBuffer strBuf = new StringBuffer();
byte[] bGBK = cnStr.getBytes();
for (int i = 0; i < bGBK.length; i++) {
strBuf.append(Integer.toHexString(bGBK[i] & 0xff));
}
return strBuf.toString();
}
/**
* 把string array or list用给定的符号symbol连接成一个字符串
*
* @param array
* @param symbol
* @return
*/
@SuppressWarnings("rawtypes")
public static String joinListToString(List array, String symbol) {
String result = "";
if (array != null) {
for (int i = 0; i < array.size(); i++) {
String temp = array.get(i).toString();
if (temp != null && temp.trim().length() > 0)
result += (temp + symbol);
}
if (result.length() > 1)
result = result.substring(0, result.length() - 1);
}
return result;
}
/**
* 截取字符串 超出的字符用symbol代替
*
* @param len
* 字符串长度 长度计量单位为一个GBK汉字 两个英文字母计算为一个单位长度
* @param str
* @param symbol
* @return
*/
public static String getLimitLengthString(String str, int len, String symbol) {
int iLen = len * 2;
int counterOfDoubleByte = 0;
String strRet = "";
try {
if (str != null) {
byte[] b = str.getBytes("GBK");
if (b.length <= iLen) {
return str;
}
for (int i = 0; i < iLen; i++) {
if (b[i] < 0) {
counterOfDoubleByte++;
}
}
if (counterOfDoubleByte % 2 == 0) {
strRet = new String(b, 0, iLen, "GBK") + symbol;
return strRet;
} else {
strRet = new String(b, 0, iLen - 1, "GBK") + symbol;
return strRet;
}
} else {
return "";
}
} catch (Exception ex) {
return str.substring(0, len);
} finally {
strRet = null;
}
}
/**
* 截取字符串 超出的字符用symbol代替
*
* @param len
* 字符串长度 长度计量单位为一个GBK汉字 两个英文字母计算为一个单位长度
* @param str
* @param symbol
* @return12
*/
public static String getLimitLengthString(String str, int len) {
return getLimitLengthString(str, len, "...");
}
/**
* 把string array or list用给定的符号symbol连接成一个字符串
*
* @param array
* @param symbol
* @return
*/
public static String joinString(String[] array, String symbol) {
String result = "";
if (array != null) {
for (int i = 0; i < array.length; i++) {
String temp = array[i];
if (temp != null && temp.trim().length() > 0)
result += (temp + symbol);
}
if (result.length() > 1)
result = result.substring(0, result.length() - 1);
}
return result;
}
/**
* 取得字符串的实际长度(考虑了汉字的情况)
*
* @param SrcStr
* 源字符串
* @return 字符串的实际长度
*/
public static int getStringLen(String SrcStr) {
int return_value = 0;
if (SrcStr != null) {
char[] theChars = SrcStr.toCharArray();
for (int i = 0; i < theChars.length; i++) {
return_value += (theChars[i] <= 255) ? 1 : 2;
}
}
return return_value;
}
/***************************************************************************
* getHideEmailPrefix - 隐藏邮件地址前缀。
*
* @param email
* - EMail邮箱地址 例如: linwenguo@koubei.com 等等...
* @return 返回已隐藏前缀邮件地址, 如 *********@koubei.com.
* @version 1.0 (2006.11.27) Wilson Lin
**************************************************************************/
public static String getHideEmailPrefix(String email) {
if (null != email) {
int index = email.lastIndexOf('@');
if (index > 0) {
email = repeatByNum("*", index).concat(email.substring(index));
}
}
return email;
}
/***************************************************************************
* repeat - 通过源字符串重复生成N次组成新的字符串。
*
* @param src
* - 源字符串 例如: 空格(" "), 星号("*"), "浙江" 等等...
* @param num
* - 重复生成次数
* @return 返回已生成的重复字符串
* @version 1.0 (2006.10.10) Wilson Lin
**************************************************************************/
public static String repeatByNum(String src, int num) {
StringBuffer s = new StringBuffer();
for (int i = 0; i < num; i++)
s.append(src);
return s.toString();
}
/**
* 格式化一个float
*
* @param format
* 要格式化成的格式 such as #.00, #.#
*/
public static String formatFloat(float f, String format) {
DecimalFormat df = new DecimalFormat(format);
return df.format(f);
}
/**
* 自定义的分隔字符串函数 例如: 1,2,3 =>[1,2,3] 3个元素 ,2,3=>[,2,3] 3个元素 ,2,3,=>[,2,3,] 4个元素
* ,,,=>[,,,] 4个元素
*
* 5.22算法修改,为提高速度不用正则表达式 两个间隔符,,返回""元素
*
* @param split
* 分割字符 默认,
* @param src
* 输入字符串
* @return 分隔后的list
* @author Robin
*/
public static List<String> splitToList(String split, String src) {
// 默认,
String sp = ",";
if (split != null && split.length() == 1) {
sp = split;
}
List<String> r = new ArrayList<String>();
int lastIndex = -1;
int index = src.indexOf(sp);
if (-1 == index && src != null) {
r.add(src);
return r;
}
while (index >= 0) {
if (index > lastIndex) {
r.add(src.substring(lastIndex + 1, index));
} else {
r.add("");
}
lastIndex = index;
index = src.indexOf(sp, index + 1);
if (index == -1) {
r.add(src.substring(lastIndex + 1, src.length()));
}
}
return r;
}
/**
* 把 名=值 参数表转换成字符串 (a=1,b=2 =>a=1&b=2)
*
* @param map
* @return
*/
@SuppressWarnings("rawtypes")
public static String linkedHashMapToString(LinkedHashMap<String, String> map) {
if (map != null && map.size() > 0) {
String result = "";
Iterator it = map.keySet().iterator();
while (it.hasNext()) {
String name = (String) it.next();
String value = (String) map.get(name);
result += (result.equals("")) ? "" : "&";
result += String.format("%s=%s", name, value);
}
return result;
}
return null;
}
/**
* 解析字符串返回 名称=值的参数表 (a=1&b=2 => a=1,b=2)
*
* @see test.koubei.util.StringUtilTest#testParseStr()
* @param str
* @return
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static LinkedHashMap<String, String> toLinkedHashMap(String str) {
if (str != null && !str.equals("") && str.indexOf("=") > 0) {
LinkedHashMap result = new LinkedHashMap();
String name = null;
String value = null;
int i = 0;
while (i < str.length()) {
char c = str.charAt(i);
switch (c) {
case 61: // =
value = "";
break;
case 38: // &
if (name != null && value != null && !name.equals("")) {
result.put(name, value);
}
name = null;
value = null;
break;
default:
if (value != null) {
value = (value != null) ? (value + c) : "" + c;
} else {
name = (name != null) ? (name + c) : "" + c;
}
}
i++;
}
if (name != null && value != null && !name.equals("")) {
result.put(name, value);
}
return result;
}
return null;
}
/**
* 数字转字符串,如果num<=0 则输出"";
*
* @param num
* @return
*/
public static String numberToString(Object num) {
if (num == null) {
return null;
} else if (num instanceof Integer && (Integer) num > 0) {
return Integer.toString((Integer) num);
} else if (num instanceof Long && (Long) num > 0) {
return Long.toString((Long) num);
} else if (num instanceof Float && (Float) num > 0) {
return Float.toString((Float) num);
} else if (num instanceof Double && (Double) num > 0) {
return Double.toString((Double) num);
} else {
return "";
}
}
/**
* 货币转字符串
*
* @param money
* @param style
* 样式 [default]要格式化成的格式 such as #.00, #.#
* @return
*/
public static String moneyToString(Object money, String style) {
if (money != null && style != null && (money instanceof Double || money instanceof Float)) {
Double num = (Double) money;
if (style.equalsIgnoreCase("default")) {
// 缺省样式 0 不输出 ,如果没有输出小数位则不输出.0
if (num == 0) {
// 不输出0
return "";
} else if ((num * 10 % 10) == 0) {
// 没有小数
return Integer.toString((int) num.intValue());
} else {
// 有小数
return num.toString();
}
} else {
DecimalFormat df = new DecimalFormat(style);
return df.format(num);
}
}
return null;
}
/**
* 在sou中是否存在finds 如果指定的finds字符串有一个在sou中找到,返回true;
*
* @param sou
* @param find
* @return
*/
public static boolean hasStr(String sou, String... finds) {
if (sou != null && finds != null && finds.length > 0) {
for (int i = 0; i < finds.length; i++) {
if (sou.indexOf(finds[i]) > -1)
return true;
}
}
return false;
}
public static boolean hasStr(String sou, List<String> finds) {
if (sou != null && finds != null && finds.size() > 0) {
for (String s : finds) {
if (sou.indexOf(s) > -1)
return true;
}
}
return false;
}
/**
* 把xml 转为object
*
* @param xml
* @return
*/
@SuppressWarnings("resource")
public static Object xmlToObject(String xml) {
try {
ByteArrayInputStream in = new ByteArrayInputStream(xml.getBytes("UTF8"));
XMLDecoder decoder = new XMLDecoder(new BufferedInputStream(in));
return decoder.readObject();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static String simpleEncrypt(String str) {
if (str != null && str.length() > 0) {
str = str.replaceAll("1", "b");
str = str.replaceAll("3", "d");
str = str.replaceAll("5", "f");
str = str.replaceAll("6", "g");
str = str.replaceAll("7", "h");
str = str.replaceAll("8", "i");
str = str.replaceAll("9", "j");
}
return str;
}
/**
* 过滤用户输入的URL地址(防治用户广告) 目前只针对以http或www开头的URL地址
* 本方法调用的正则表达式,不建议用在对性能严格的地方例如:循环及list页面等
*
* @author fengliang
* @param str
* 需要处理的字符串
* @return 返回处理后的字符串
*/
public static String removeURL(String str) {
if (str != null)
str = str.toLowerCase().replaceAll("(http|www|com|cn|org|\\.)+", "");
return str;
}
/**
* Wap页面的非法字符检查
*
* @author hugh115
* @date 2007-06-29
* @param str
* @return
*/
public static String replaceWapStr(String str) {
if (str != null) {
str = str.replaceAll("<span class=\"keyword\">", "");
str = str.replaceAll("</span>", "");
str = str.replaceAll("<strong class=\"keyword\">", "");
str = str.replaceAll("<strong>", "");
str = str.replaceAll("</strong>", "");
str = str.replace('$', '$');
str = str.replaceAll("&", "&");
str = str.replace('&', '&');
str = str.replace('<', '<');
str = str.replace('>', '>');
}
return str;
}
/**
* 页面中去除字符串中的空格、回车、换行符、制表符
*
* @author shazao
* @date 2007-08-17
* @param str
* @return
*/
public static String replaceBlank(String str) {
if (str != null) {
Pattern p = Pattern.compile("\\s*|\t|\r|\n");
Matcher m = p.matcher(str);
str = m.replaceAll("");
}
return str;
}
/**
* 全角生成半角
*
* @author bailong
* @date 2007-08-29
* @param str
* @return
*/
public static String Q2B(String QJstr) {
String outStr = "";
String Tstr = "";
byte[] b = null;
for (int i = 0; i < QJstr.length(); i++) {
try {
Tstr = QJstr.substring(i, i + 1);
b = Tstr.getBytes("unicode");
} catch (java.io.UnsupportedEncodingException e) {
}
if (b[3] == -1) {
b[2] = (byte) (b[2] + 32);
b[3] = 0;
try {
outStr = outStr + new String(b, "unicode");
} catch (java.io.UnsupportedEncodingException ex) {
}
} else {
outStr = outStr + Tstr;
}
}
return outStr;
}
/**
*
* 转换编码
*
* @param s
* 源字符串
* @param fencode
* 源编码格式
* @param bencode
* 目标编码格式
* @return 目标编码
*/
public static String changeEncoding(String s, String sourceCode, String targetCode) {
String str;
try {
if (StringUtils.isNotEmpty(s)) {
str = new String(s.getBytes(sourceCode), targetCode);
} else {
str = "";
}
return str;
} catch (UnsupportedEncodingException e) {
return s;
}
}
/**
* @param str
* @return
*************************************************************************
*/
public static String removeHTMLLableExe(String str) {
str = stringReplace(str, ">\\s*<", "><");
str = stringReplace(str, " ", " ");// 替换空格
str = stringReplace(str, "<br ?/?>", "\n");// 去<br><br />
str = stringReplace(str, "<([^<>]+)>", "");// 去掉<>内的字符
str = stringReplace(str, "\\s\\s\\s*", " ");// 将多个空白变成一个空格
str = stringReplace(str, "^\\s*", "");// 去掉头的空白
str = stringReplace(str, "\\s*$", "");// 去掉尾的空白
str = stringReplace(str, " +", " ");
return str;
}
/**
* 除去html标签
*
* @param str
* 源字符串
* @return 目标字符串
*/
public static String removeHTMLLable(String str) {
str = stringReplace(str, "\\s", "");// 去掉页面上看不到的字符
str = stringReplace(str, "<br ?/?>", "\n");// 去<br><br />
str = stringReplace(str, "<([^<>]+)>", "");// 去掉<>内的字符
str = stringReplace(str, " ", " ");// 替换空格
str = stringReplace(str, "&(\\S)(\\S?)(\\S?)(\\S?);", "");// 去<br><br />
return str;
}
/**
* 去掉HTML标签之外的字符串
*
* @param str
* 源字符串
* @return 目标字符串
*/
public static String removeOutHTMLLable(String str) {
str = stringReplace(str, ">([^<>]+)<", "><");
str = stringReplace(str, "^([^<>]+)<", "<");
str = stringReplace(str, ">([^<>]+)$", ">");
return str;
}
/**
*
* 字符串替换
*
* @param str
* 源字符串
* @param sr
* 正则表达式样式
* @param sd
* 替换文本
* @return 结果串
*/
public static String stringReplace(String str, String regEx, String sd) {
Pattern p = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(str);
return m.replaceAll(sd);
}
/**
*
* 根据正则表达式分割字符串
*
* @param str
* 源字符串
* @param ms
* 正则表达式
* @return 目标字符串组
*/
public static String[] splitString(String str, String ms) {
String regEx = ms;
Pattern p = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);
String[] sp = p.split(str);
return sp;
}
/**
* 根据正则表达式提取字符串,相同的字符串只返回一个
*
* @param str源字符串
* @param pattern
* 正则表达式
* @return 目标字符串数据组
*************************************************************************
*/
// ★传入一个字符串,把符合pattern格式的字符串放入字符串数组
// java.util.regex是一个用正则表达式所订制的模式来对字符串进行匹配工作的类库包
public static String[] getStringArrayByPattern(String str, String pattern) {
Pattern p = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
Matcher matcher = p.matcher(str);
// 范型
Set<String> result = new HashSet<String>();// 目的是:相同的字符串只返回一个。。。 不重复元素
// boolean find() 尝试在目标字符串里查找下一个匹配子串。
while (matcher.find()) {
for (int i = 0; i < matcher.groupCount(); i++) { // int groupCount()
// 返回当前查找所获得的匹配组的数量。
// org.jeecgframework.core.util.LogUtil.info(matcher.group(i));
result.add(matcher.group(i));
}
}
String[] resultStr = null;
if (result.size() > 0) {
resultStr = new String[result.size()];
return result.toArray(resultStr);// 将Set result转化为String[] resultStr
}
return resultStr;
}
/**
* 带有前一次替代序列的正则表达式替代
*
* @param s
* @param pf
* @param pb
* @param start
* @return
*/
public static String stringReplace(String s, String pf, String pb, int start) {
Pattern pattern_hand = Pattern.compile(pf);
Matcher matcher_hand = pattern_hand.matcher(s);
int gc = matcher_hand.groupCount();
int pos = start;
String sf1 = "";
String sf2 = "";
String sf3 = "";
int if1 = 0;
String strr = "";
while (matcher_hand.find(pos)) {
sf1 = matcher_hand.group();
if1 = s.indexOf(sf1, pos);
if (if1 >= pos) {
strr += s.substring(pos, if1);
pos = if1 + sf1.length();
sf2 = pb;
for (int i = 1; i <= gc; i++) {
sf3 = "\\" + i;
sf2 = replaceAll(sf2, sf3, matcher_hand.group(i));
}
strr += sf2;
} else {
return s;
}
}
strr = s.substring(0, start) + strr;
return strr;
}
/**
* 存文本替换
*
* @param s
* 源字符串
* @param sf
* 子字符串
* @param sb
* 替换字符串
* @return 替换后的字符串
*/
public static String replaceAll(String s, String sf, String sb) {
int i = 0, j = 0;
int l = sf.length();
boolean b = true;
boolean o = true;
String str = "";
do {
j = i;
i = s.indexOf(sf, j);
if (i > j) {
str += s.substring(j, i);
str += sb;
i += l;
o = false;
} else {
str += s.substring(j);
b = false;
}
} while (b);
if (o) {
str = s;
}
return str;
}
/**
* 判断是否与给定字符串样式匹配
*
* @param str
* 字符串
* @param pattern
* 正则表达式样式
* @return 是否匹配是true,否false
*/
public static boolean isMatch(String str, String pattern) {
Pattern pattern_hand = Pattern.compile(pattern);
Matcher matcher_hand = pattern_hand.matcher(str);
return matcher_hand.matches();
}
/**
* 截取字符串
*
* @param s
* 源字符串
* @param jmp
* 跳过jmp
* @param sb
* 取在sb
* @param se
* 于se
* @return 之间的字符串
*/
public static String subStringExe(String s, String jmp, String sb, String se) {
if (isEmpty(s)) {
return "";
}
int i = s.indexOf(jmp);
if (i >= 0 && i < s.length()) {
s = s.substring(i + 1);
}
i = s.indexOf(sb);
if (i >= 0 && i < s.length()) {
s = s.substring(i + 1);
}
if (se == "") {
return s;
} else {
i = s.indexOf(se);
if (i >= 0 && i < s.length()) {
s = s.substring(i + 1);
}
return s;
}
}
/**
* *************************************************************************
* 用要通过URL传输的内容进行编码
*
* @param 源字符串
* @return 经过编码的内容
*************************************************************************
*/
public static String URLEncode(String src) {
String return_value = "";
try {
if (src != null) {
return_value = URLEncoder.encode(src, "GBK");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return_value = src;
}
return return_value;
}
/**
* *************************************************************************
*
* @author 李锋 2007.4.18
* @param 传入
* 福test照楼(北大门&#
* 24635 ;店)福
* @return 经过解码的内容
*************************************************************************
*/
public static String getGBK(String str) {
return transfer(str);
}
public static String transfer(String str) {
Pattern p = Pattern.compile("&#\\d+;");
Matcher m = p.matcher(str);
while (m.find()) {
String old = m.group();
str = str.replaceAll(old, getChar(old));
}
return str;
}
public static String getChar(String str) {
String dest = str.substring(2, str.length() - 1);
char ch = (char) Integer.parseInt(dest);
return "" + ch;
}
/**
* 泛型方法(通用),把list转换成以“,”相隔的字符串 调用时注意类型初始化(申明类型) 如:List<Integer> intList = new
* ArrayList<Integer>(); 调用方法:StringUtil.listTtoString(intList);
* 效率:list中4条信息,1000000次调用时间为850ms左右
*
* @author fengliang
* @serialData 2008-01-09
* @param <T>
* 泛型
* @param list
* list列表
* @return 以“,”相隔的字符串
*/
public static <T> String listTtoString(List<T> list) {
if (list == null || list.size() < 1)
return "";
Iterator<T> i = list.iterator();
if (!i.hasNext())
return "";
StringBuilder sb = new StringBuilder();
for (;;) {
T e = i.next();
sb.append(e);
if (!i.hasNext())
return sb.toString();
sb.append(",");
}
}
/**
* 把整形数组转换成以“,”相隔的字符串
*
* @author fengliang
* @serialData 2008-01-08
* @param a
* 数组a
* @return 以“,”相隔的字符串
*/
public static String intArraytoString(int[] a) {
if (a == null)
return "";
int iMax = a.length - 1;
if (iMax == -1)
return "";
StringBuilder b = new StringBuilder();
for (int i = 0;; i++) {
b.append(a[i]);
if (i == iMax)
return b.toString();
b.append(",");
}
}
/**
* 判断文字内容重复
*
* @author 沙枣
* @Date 2008-04-17
*/
public static boolean isContentRepeat(String content) {
int similarNum = 0;
int forNum = 0;
int subNum = 0;
int thousandNum = 0;
String startStr = "";
String nextStr = "";
boolean result = false;
float endNum = (float) 0.0;
if (content != null && content.length() > 0) {
if (content.length() % 1000 > 0)
thousandNum = (int) Math.floor(content.length() / 1000) + 1;
else
thousandNum = (int) Math.floor(content.length() / 1000);
if (thousandNum < 3)
subNum = 100 * thousandNum;
else if (thousandNum < 6)
subNum = 200 * thousandNum;
else if (thousandNum < 9)
subNum = 300 * thousandNum;
else
subNum = 3000;
for (int j = 1; j < subNum; j++) {
if (content.length() % j > 0)
forNum = (int) Math.floor(content.length() / j) + 1;
else
forNum = (int) Math.floor(content.length() / j);
if (result || j >= content.length())
break;
else {
for (int m = 0; m < forNum; m++) {
if (m * j > content.length() || (m + 1) * j > content.length() || (m + 2) * j > content.length())
break;
startStr = content.substring(m * j, (m + 1) * j);
nextStr = content.substring((m + 1) * j, (m + 2) * j);
if (startStr.equals(nextStr)) {
similarNum = similarNum + 1;
endNum = (float) similarNum / forNum;
if (endNum > 0.4) {
result = true;
break;
}
} else
similarNum = 0;
}
}
}
}
return result;
}
/**
* 判断对象是否为空
*
* @param str
* @return
*/
public static boolean isNotEmpty(Object str) {
boolean flag = true;
if (str != null && !str.equals("")) {
if (str.toString().length() > 0) {
flag = true;
}
} else {
flag = false;
}
return flag;
}
/**
* 全角字符变半角字符
*
* @author shazao
* @date 2008-04-03
* @param str
* @return
*/
public static String full2Half(String str) {
if (str == null || "".equals(str))
return "";
StringBuffer sb = new StringBuffer();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c >= 65281 && c < 65373)
sb.append((char) (c - 65248));
else
sb.append(str.charAt(i));
}
return sb.toString();
}
/**
* 全角括号转为半角
*
* @author shazao
* @date 2007-11-29
* @param str
* @return
*/
public static String replaceBracketStr(String str) {
if (str != null && str.length() > 0) {
str = str.replaceAll("(", "(");
str = str.replaceAll(")", ")");
}
return str;
}
/**
* 解析字符串返回map键值对(例:a=1&b=2 => a=1,b=2)
*
* @param query
* 源参数字符串
* @param split1
* 键值对之间的分隔符(例:&)
* @param split2
* key与value之间的分隔符(例:=)
* @param dupLink
* 重复参数名的参数值之间的连接符,连接后的字符串作为该参数的参数值,可为null
* null:不允许重复参数名出现,则靠后的参数值会覆盖掉靠前的参数值。
* @return map
* @author sky
*/
@SuppressWarnings("unchecked")
public static Map<String, String> parseQuery(String query, char split1, char split2, String dupLink) {
if (!isEmpty(query) && query.indexOf(split2) > 0) {
@SuppressWarnings("rawtypes")
Map<String, String> result = new HashMap();
String name = null;
String value = null;
String tempValue = "";
int len = query.length();
for (int i = 0; i < len; i++) {
char c = query.charAt(i);
if (c == split2) {
value = "";
} else if (c == split1) {
if (!isEmpty(name) && value != null) {
if (dupLink != null) {
tempValue = result.get(name);
if (tempValue != null) {
value += dupLink + tempValue;
}
}
result.put(name, value);
}
name = null;
value = null;
} else if (value != null) {
value += c;
} else {
name = (name != null) ? (name + c) : "" + c;
}
}
if (!isEmpty(name) && value != null) {
if (dupLink != null) {
tempValue = result.get(name);
if (tempValue != null) {
value += dupLink + tempValue;
}
}
result.put(name, value);
}
return result;
}
return null;
}
/**
* 获取从start开始用*替换len个长度后的字符串
*
* @param str
* 要替换的字符串
* @param start
* 开始位置
* @param len
* 长度
* @return 替换后的字符串
*/
public static String getMaskStr(String str, int start, int len) {
if (StringUtils.isEmpty(str)) {
return str;
}
if (str.length() < start) {
return str;
}
// 获取*之前的字符串
String ret = str.substring(0, start);
// 获取最多能打的*个数
int strLen = str.length();
if (strLen < start + len) {
len = strLen - start;
}
// 替换成*
for (int i = 0; i < len; i++) {
ret += "*";
}
// 加上*之后的字符串
if (strLen > start + len) {
ret += str.substring(start + len);
}
return ret;
}
// 截取数字
public String splitNumbers(String content) {
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(content);
while (matcher.find()) {
return matcher.group(0);
}
return "";
}
// 截取非数字
public String splitNotNumber(String content) {
Pattern pattern = Pattern.compile("\\D+");
Matcher matcher = pattern.matcher(content);
while (matcher.find()) {
return matcher.group(0);
}
return "";
}
/**
* 判断某个字符串是否存在于数组中
*
* @param stringArray
* 原数组
* @param source
* 查找的字符串
* @return 是否找到
*/
public static boolean contains(String[] stringArray, String source) {
// 转换为list
List<String> tempList = Arrays.asList(stringArray);
// 利用list的包含方法,进行判断
if (tempList.contains(source)) {
return true;
} else {
return false;
}
}
/**
* 判断这个类是不是java自带的类
*
* @param clazz
* @return
*/
public static boolean isJavaClass(Class<?> clazz) {
boolean isBaseClass = false;
if (clazz.isArray()) {
isBaseClass = false;
} else if (clazz.isPrimitive() || clazz.getPackage() == null || clazz.getPackage().getName().equals("java.lang") || clazz.getPackage().getName().equals("java.math")
|| clazz.getPackage().getName().equals("java.util")) {
isBaseClass = true;
}
return isBaseClass;
}
/**
* 检查字符串是否是空白:null、空字符串""或只有空白字符。
*
* @param str
* 要检查的字符串
* @return 如果为空白, 则返回true
*/
public static boolean isEmpty(String str) {
int length;
if ((str == null) || "".equals(str) || ((length = str.length()) == 0)) {
return true;
}
for (int i = 0; i < length; i++) {
if (!Character.isWhitespace(str.charAt(i))) {
return false;
}
}
return true;
}
/**
* 检查字符串是否不是空白:null、空字符串""或只有空白字符。
*
* @param str
* 要检查的字符串
* @return 如果为空白, 则返回true
*/
public static boolean isNotEmpty(String str) {
int length;
if ((str == null) || ((length = str.length()) == 0) || "".equals(str)) {
return false;
}
for (int i = 0; i < length; i++) {
if (!Character.isWhitespace(str.charAt(i))) {
return true;
}
}
return false;
}
/**
* 如果字符串是null,则返回空字符串"",否则返回字符串本身。
*
* @param str
* 要转换的字符串
* @return 字符串本身或空字符串""
*/
public static String defaultIfNull(String str) {
return (str == null) ? "" : str;
}
/**
* 将半角的符号转换成全角符号.(即英文字符转中文字符)
*
* @autor:chenssy
* @date:2014年8月7日
*
* @param str
* 要转换的字符
* @return
*/
public static String changeToFull(String str) {
String source = "1234567890!@#$%^&*()abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_=+\\|[];:'\",<.>/?";
String[] decode = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "!", "@", "#", "$", "%", "︿", "&", "*", "(", ")", "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", "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", "-", "_", "=", "+", "\", "|", "【", "】", ";", ":", "'", "\"", ",", "〈", "。", "〉", "/", "?" };
String result = "";
for (int i = 0; i < str.length(); i++) {
int pos = source.indexOf(str.charAt(i));
if (pos != -1) {
result += decode[pos];
} else {
result += str.charAt(i);
}
}
return result;
}
/**
* 将字符转换为编码为Unicode,格式 为'\u0020'<br>
* unicodeEscaped(' ') = "\u0020"<br>
* unicodeEscaped('A') = "\u0041"
*
* @autor:chenssy
* @date:2014年8月7日
*
* @param ch
* 待转换的char 字符
* @return
*/
public static String unicodeEscaped(char ch) {
if (ch < 0x10) {
return "\\u000" + Integer.toHexString(ch);
} else if (ch < 0x100) {
return "\\u00" + Integer.toHexString(ch);
} else if (ch < 0x1000) {
return "\\u0" + Integer.toHexString(ch);
}
return "\\u" + Integer.toHexString(ch);
}
/**
* 进行toString操作,若为空,返回默认值
*
* @autor:chenssy
* @date:2014年8月9日
*
* @param object
* 要进行toString操作的对象
* @param nullStr
* 返回的默认值
* @return
*/
public static String toString(Object object, String nullStr) {
return object == null ? nullStr : object.toString();
}
/**
* 将字符串重复N次,null、""不在循环次数里面 <br>
* 当value == null || value == "" return value;<br>
* 当count <= 1 返回 value
*
* @autor:chenssy
* @date:2014年8月9日
*
* @param value
* 需要循环的字符串
* @param count
* 循环的次数
* @return
*/
public static String repeatString(String value, int count) {
if (value == null || "".equals(value) || count <= 1) {
return value;
}
int length = value.length();
if (length == 1) { // 长度为1,存在字符
return repeatChar(value.charAt(0), count);
}
int outputLength = length * count;
switch (length) {
case 1:
return repeatChar(value.charAt(0), count);
case 2:
char ch0 = value.charAt(0);
char ch1 = value.charAt(1);
char[] output2 = new char[outputLength];
for (int i = count * 2 - 2; i >= 0; i--, i--) {
output2[i] = ch0;
output2[i + 1] = ch1;
}
return new String(output2);
default:
StringBuilder buf = new StringBuilder(outputLength);
for (int i = 0; i < count; i++) {
buf.append(value);
}
return buf.toString();
}
/**
* 将某个字符重复N次
*
* @autor:chenssy
* @date:2014年8月9日
*
* @param ch
* 需要循环的字符
* @param count
* 循环的次数
* @return
*/
public static String repeatChar(char ch, int count) {
char[] buf = new char[count];
for (int i = count - 1; i >= 0; i--) {
buf[i] = ch;
}
return new String(buf);
}
}