StringUtil.java 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777
  1. package com.xunao.effectdemo.utils;
  2. import java.io.BufferedReader;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.io.InputStreamReader;
  6. import java.math.BigDecimal;
  7. import java.text.DecimalFormat;
  8. import java.text.NumberFormat;
  9. import java.text.ParseException;
  10. import java.text.SimpleDateFormat;
  11. import java.util.Calendar;
  12. import java.util.Date;
  13. import java.util.TimeZone;
  14. import java.util.regex.Pattern;
  15. public class StringUtil {
  16. private final static String FSpliter = "##";
  17. private final static String SSpliter = "||";
  18. private final static Pattern PHONE = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
  19. private final static Pattern emailer = Pattern
  20. .compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
  21. private final static Pattern IMG_URL = Pattern
  22. .compile(".*?(gif|jpeg|png|jpg|bmp)");
  23. private final static Pattern URL = Pattern
  24. .compile("^(https|http)://.*?$(net|com|.com.cn|org|me|)");
  25. private final static ThreadLocal<SimpleDateFormat> dateFormater = new ThreadLocal<SimpleDateFormat>() {
  26. @Override
  27. protected SimpleDateFormat initialValue() {
  28. return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  29. }
  30. };
  31. private final static ThreadLocal<SimpleDateFormat> dateFormater2 = new ThreadLocal<SimpleDateFormat>() {
  32. @Override
  33. protected SimpleDateFormat initialValue() {
  34. return new SimpleDateFormat("yyyy-MM-dd");
  35. }
  36. };
  37. /**
  38. * 将字符串转位日期类型
  39. *
  40. * @param sdate
  41. * @return
  42. */
  43. public static Date toDate(String sdate) {
  44. return toDate(sdate, dateFormater.get());
  45. }
  46. public static Date toDate(String sdate, SimpleDateFormat dateFormater) {
  47. try {
  48. return dateFormater.parse(sdate);
  49. } catch (ParseException e) {
  50. return null;
  51. }
  52. }
  53. public static String getDateString(Date date) {
  54. return dateFormater.get().format(date);
  55. }
  56. /**
  57. * 以友好的方式显示时间
  58. *
  59. * @param sdate
  60. * @return
  61. */
  62. public static String friendly_time(String sdate) {
  63. Date time = null;
  64. if (TimeZoneUtil.isInEasternEightZones())
  65. time = toDate(sdate);
  66. else
  67. time = TimeZoneUtil.transformTime(toDate(sdate),
  68. TimeZone.getTimeZone("GMT+08"), TimeZone.getDefault());
  69. if (time == null) {
  70. return "Unknown";
  71. }
  72. String ftime = "";
  73. Calendar cal = Calendar.getInstance();
  74. // 判断是否是同一天
  75. String curDate = dateFormater2.get().format(cal.getTime());
  76. String paramDate = dateFormater2.get().format(time);
  77. if (curDate.equals(paramDate)) {
  78. int hour = (int) ((cal.getTimeInMillis() - time.getTime()) / 3600000);
  79. if (hour == 0)
  80. ftime = Math.max(
  81. (cal.getTimeInMillis() - time.getTime()) / 60000, 1)
  82. + "分钟前";
  83. else
  84. ftime = hour + "小时前";
  85. return ftime;
  86. }
  87. long lt = time.getTime() / 86400000;
  88. long ct = cal.getTimeInMillis() / 86400000;
  89. int days = (int) (ct - lt);
  90. if (days == 0) {
  91. int hour = (int) ((cal.getTimeInMillis() - time.getTime()) / 3600000);
  92. if (hour == 0)
  93. ftime = Math.max(
  94. (cal.getTimeInMillis() - time.getTime()) / 60000, 1)
  95. + "分钟前";
  96. else
  97. ftime = hour + "小时前";
  98. } else if (days == 1) {
  99. ftime = "昨天";
  100. } else if (days == 2) {
  101. ftime = "前天 ";
  102. } else if (days > 2 && days < 31) {
  103. ftime = days + "天前";
  104. } else if (days >= 31 && days <= 2 * 31) {
  105. ftime = "一个月前";
  106. } else if (days > 2 * 31 && days <= 3 * 31) {
  107. ftime = "2个月前";
  108. } else if (days > 3 * 31 && days <= 4 * 31) {
  109. ftime = "3个月前";
  110. } else {
  111. ftime = dateFormater2.get().format(time);
  112. }
  113. return ftime;
  114. }
  115. public static String friendly_time2(String sdate) {
  116. String res = "";
  117. if (isEmpty(sdate))
  118. return "";
  119. String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
  120. String currentData = StringUtil.getDataTime("MM-dd");
  121. int currentDay = toInt(currentData.substring(3));
  122. int currentMoth = toInt(currentData.substring(0, 2));
  123. int sMoth = toInt(sdate.substring(5, 7));
  124. int sDay = toInt(sdate.substring(8, 10));
  125. int sYear = toInt(sdate.substring(0, 4));
  126. Date dt = new Date(sYear, sMoth - 1, sDay - 1);
  127. if (sDay == currentDay && sMoth == currentMoth) {
  128. res = "今天 / " + weekDays[getWeekOfDate(new Date())];
  129. } else if (sDay == currentDay + 1 && sMoth == currentMoth) {
  130. res = "昨天 / " + weekDays[(getWeekOfDate(new Date()) + 6) % 7];
  131. } else {
  132. if (sMoth < 10) {
  133. res = "0";
  134. }
  135. res += sMoth + "/";
  136. if (sDay < 10) {
  137. res += "0";
  138. }
  139. res += sDay + " / " + weekDays[getWeekOfDate(dt)];
  140. }
  141. return res;
  142. }
  143. /**
  144. * 获取当前日期是星期几<br>
  145. *
  146. * @param dt
  147. * @return 当前日期是星期几
  148. */
  149. public static int getWeekOfDate(Date dt) {
  150. Calendar cal = Calendar.getInstance();
  151. cal.setTime(dt);
  152. int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
  153. if (w < 0)
  154. w = 0;
  155. return w;
  156. }
  157. /**
  158. * 判断给定字符串时间是否为今日
  159. *
  160. * @param sdate
  161. * @return boolean
  162. */
  163. public static boolean isToday(String sdate) {
  164. boolean b = false;
  165. Date time = toDate(sdate);
  166. Date today = new Date();
  167. if (time != null) {
  168. String nowDate = dateFormater2.get().format(today);
  169. String timeDate = dateFormater2.get().format(time);
  170. if (nowDate.equals(timeDate)) {
  171. b = true;
  172. }
  173. }
  174. return b;
  175. }
  176. /**
  177. * 返回long类型的今天的日期
  178. *
  179. * @return
  180. */
  181. public static long getToday() {
  182. Calendar cal = Calendar.getInstance();
  183. String curDate = dateFormater2.get().format(cal.getTime());
  184. curDate = curDate.replace("-", "");
  185. return Long.parseLong(curDate);
  186. }
  187. public static String getCurTimeStr() {
  188. Calendar cal = Calendar.getInstance();
  189. String curDate = dateFormater.get().format(cal.getTime());
  190. return curDate;
  191. }
  192. /***
  193. * 计算两个时间差,返回的是的秒s
  194. *
  195. * @param dete1
  196. * @param date2
  197. * @return
  198. * @author 火蚁 2015-2-9 下午4:50:06
  199. */
  200. public static long calDateDifferent(String dete1, String date2) {
  201. long diff = 0;
  202. Date d1 = null;
  203. Date d2 = null;
  204. try {
  205. d1 = dateFormater.get().parse(dete1);
  206. d2 = dateFormater.get().parse(date2);
  207. // 毫秒ms
  208. diff = d2.getTime() - d1.getTime();
  209. } catch (Exception e) {
  210. e.printStackTrace();
  211. }
  212. return diff / 1000;
  213. }
  214. public static String getChineseForNum(int num) {
  215. String chineseNum = "";
  216. switch (num) {
  217. case 0:
  218. chineseNum = "零";
  219. break;
  220. case 1:
  221. chineseNum = "一";
  222. break;
  223. case 2:
  224. chineseNum = "二";
  225. break;
  226. case 3:
  227. chineseNum = "三";
  228. break;
  229. case 4:
  230. chineseNum = "四";
  231. break;
  232. case 5:
  233. chineseNum = "五";
  234. break;
  235. case 6:
  236. chineseNum = "六";
  237. break;
  238. case 7:
  239. chineseNum = "七";
  240. break;
  241. case 8:
  242. chineseNum = "八";
  243. break;
  244. case 9:
  245. chineseNum = "九";
  246. break;
  247. case 10:
  248. chineseNum = "十";
  249. break;
  250. }
  251. return chineseNum;
  252. }
  253. /**
  254. * 判断给定字符串是否空白串。 空白串是指由空格、制表符、回车符、换行符组成的字符串 若输入字符串为null或空字符串,返回true
  255. *
  256. * @param input
  257. * @return boolean
  258. */
  259. public static boolean isEmpty(String input) {
  260. if (input == null || "".equals(input))
  261. return true;
  262. for (int i = 0; i < input.length(); i++) {
  263. char c = input.charAt(i);
  264. if (c != ' ' && c != '\t' && c != '\r' && c != '\n') {
  265. return false;
  266. }
  267. }
  268. return true;
  269. }
  270. public static boolean isPhone(String phone) {
  271. if (phone == null || phone.trim().length() == 0) {
  272. return false;
  273. }
  274. return PHONE.matcher(phone).matches();
  275. }
  276. /**
  277. * 判断是不是一个合法的电子邮件地址
  278. *
  279. * @param email
  280. * @return
  281. */
  282. public static boolean isEmail(String email) {
  283. if (email == null || email.trim().length() == 0)
  284. return false;
  285. return emailer.matcher(email).matches();
  286. }
  287. /**
  288. * 判断一个url是否为图片url
  289. *
  290. * @param url
  291. * @return
  292. */
  293. public static boolean isImgUrl(String url) {
  294. if (url == null || url.trim().length() == 0)
  295. return false;
  296. return IMG_URL.matcher(url).matches();
  297. }
  298. /**
  299. * 判断是否为一个合法的url地址
  300. *
  301. * @param str
  302. * @return
  303. */
  304. public static boolean isUrl(String str) {
  305. if (str == null || str.trim().length() == 0)
  306. return false;
  307. return URL.matcher(str).matches();
  308. }
  309. /**
  310. * 字符串转整数
  311. *
  312. * @param str
  313. * @param defValue
  314. * @return
  315. */
  316. public static int toInt(String str, int defValue) {
  317. try {
  318. return Integer.parseInt(str);
  319. } catch (Exception e) {
  320. }
  321. return defValue;
  322. }
  323. /**
  324. * 对象转整数
  325. *
  326. * @param obj
  327. * @return 转换异常返回 0
  328. */
  329. public static int toInt(Object obj) {
  330. if (obj == null)
  331. return 0;
  332. return toInt(obj.toString(), 0);
  333. }
  334. /**
  335. * 对象转整数
  336. *
  337. * @param obj
  338. * @return 转换异常返回 0
  339. */
  340. public static long toLong(String obj) {
  341. try {
  342. return Long.parseLong(obj);
  343. } catch (Exception e) {
  344. }
  345. return 0;
  346. }
  347. /**
  348. * 字符串转布尔值
  349. *
  350. * @param b
  351. * @return 转换异常返回 false
  352. */
  353. public static boolean toBool(String b) {
  354. try {
  355. return Boolean.parseBoolean(b);
  356. } catch (Exception e) {
  357. }
  358. return false;
  359. }
  360. public static String getString(String s) {
  361. return s == null ? "" : s;
  362. }
  363. /**
  364. * 将一个InputStream流转换成字符串
  365. *
  366. * @param is
  367. * @return
  368. */
  369. public static String toConvertString(InputStream is) {
  370. StringBuffer res = new StringBuffer();
  371. InputStreamReader isr = new InputStreamReader(is);
  372. BufferedReader read = new BufferedReader(isr);
  373. try {
  374. String line;
  375. line = read.readLine();
  376. while (line != null) {
  377. res.append(line + "<br>");
  378. line = read.readLine();
  379. }
  380. } catch (IOException e) {
  381. e.printStackTrace();
  382. } finally {
  383. try {
  384. if (null != isr) {
  385. isr.close();
  386. isr.close();
  387. }
  388. if (null != read) {
  389. read.close();
  390. read = null;
  391. }
  392. if (null != is) {
  393. is.close();
  394. is = null;
  395. }
  396. } catch (IOException e) {
  397. }
  398. }
  399. return res.toString();
  400. }
  401. /***
  402. * 截取字符串
  403. *
  404. * @param start 从那里开始,0算起
  405. * @param num 截取多少个
  406. * @param str 截取的字符串
  407. * @return
  408. */
  409. public static String getSubString(int start, int num, String str) {
  410. if (str == null) {
  411. return "";
  412. }
  413. int leng = str.length();
  414. if (start < 0) {
  415. start = 0;
  416. }
  417. if (start > leng) {
  418. start = leng;
  419. }
  420. if (num < 0) {
  421. num = 1;
  422. }
  423. int end = start + num;
  424. if (end > leng) {
  425. end = leng;
  426. }
  427. return str.substring(start, end);
  428. }
  429. /**
  430. * 获取当前时间为每年第几周
  431. *
  432. * @return
  433. */
  434. public static int getWeekOfYear() {
  435. return getWeekOfYear(new Date());
  436. }
  437. /**
  438. * 获取当前时间为每年第几周
  439. *
  440. * @param date
  441. * @return
  442. */
  443. public static int getWeekOfYear(Date date) {
  444. Calendar c = Calendar.getInstance();
  445. c.setFirstDayOfWeek(Calendar.MONDAY);
  446. c.setTime(date);
  447. int week = c.get(Calendar.WEEK_OF_YEAR) - 1;
  448. week = week == 0 ? 52 : week;
  449. return week > 0 ? week : 1;
  450. }
  451. public static int[] getCurrentDate() {
  452. int[] dateBundle = new int[3];
  453. String[] temp = getDataTime("yyyy-MM-dd").split("-");
  454. for (int i = 0; i < 3; i++) {
  455. try {
  456. dateBundle[i] = Integer.parseInt(temp[i]);
  457. } catch (Exception e) {
  458. dateBundle[i] = 0;
  459. }
  460. }
  461. return dateBundle;
  462. }
  463. /**
  464. * 返回当前系统时间
  465. */
  466. public static String getDataTime(String format) {
  467. SimpleDateFormat df = new SimpleDateFormat(format);
  468. return df.format(new Date());
  469. }
  470. /**
  471. * 将一个InputStream流转换成字符串,UTF-8
  472. */
  473. public static String inputStream2String(InputStream is, String code) throws IOException {
  474. BufferedReader in = new BufferedReader(new InputStreamReader(is, code));
  475. int i = -1;
  476. char[] b = new char[1000];
  477. StringBuffer sb = new StringBuffer();
  478. while ((i = in.read(b)) != -1) {
  479. sb.append(new String(b, 0, i));
  480. }
  481. String content = sb.toString();
  482. return content;
  483. }
  484. /**
  485. * 将一个替换一个字符串中的某几个字符
  486. */
  487. public static String replaceStringForPosition(String res, String str, int start, int end) {
  488. String head = res.substring(0, start - 1);
  489. String body = str;
  490. String tail = res.substring(end - 1);
  491. return head + body + tail;
  492. }
  493. public static String getWanMoney(double money) {
  494. double tempDouble = money / 10000;
  495. if (tempDouble < 1) {
  496. return String.valueOf((int) money);
  497. } else {
  498. NumberFormat nf = new DecimalFormat("#.#");
  499. String strMoney = nf.format(tempDouble) + "万";
  500. return strMoney;
  501. }
  502. }
  503. public static String getFormatMoney(double money) {
  504. NumberFormat nf = new DecimalFormat(",###");
  505. String strMoney = nf.format(money);
  506. return strMoney;
  507. }
  508. public static String getFormatMoneyOnePoint(double money) {
  509. DecimalFormat nf = new DecimalFormat("#.#");
  510. String strMoney = nf.format(new BigDecimal(money));
  511. String[] strsTmp = strMoney.split("\\.");
  512. if (strsTmp.length < 2) {
  513. strMoney = strMoney + ".0";
  514. } else {
  515. if (strsTmp[1].length() > 1) {
  516. strsTmp[1] = strsTmp[1].substring(0, 1);
  517. }
  518. strMoney = strsTmp[0] + "." + strsTmp[1];
  519. }
  520. return strMoney;
  521. }
  522. public static String getFormatMoneyTwoPoint(double money) {
  523. DecimalFormat nf = new DecimalFormat("#.##");
  524. String strMoney = nf.format(new BigDecimal(money));
  525. String[] strsTmp = strMoney.split("\\.");
  526. if (strsTmp.length < 2) {
  527. strMoney = strMoney + ".00";
  528. } else {
  529. if (strsTmp[1].length() == 1) {
  530. strsTmp[1] = strsTmp[1] + "0";
  531. }
  532. if (strsTmp[1].length() > 2) {
  533. strsTmp[1] = strsTmp[1].substring(0, 2);
  534. }
  535. strMoney = strsTmp[0] + "." + strsTmp[1];
  536. }
  537. return strMoney;
  538. }
  539. public static String getFormatMoneyTwoPointFen(long money) {
  540. String strMoney = String.valueOf(money);
  541. strMoney = strMoney.substring(0, strMoney.length() - 2) + "." + strMoney.substring(strMoney.length() - 2);
  542. return strMoney;
  543. }
  544. public static String[] splitStringsWithSpace(String source) {
  545. if (StringUtil.isEmpty(source)) {
  546. return null;
  547. }
  548. source = source + " .";
  549. String tempSource = source.replace("[", "").replace("]", "");
  550. String[] tempStrs = tempSource.split(" ");
  551. String[] strs = new String[tempStrs.length - 1];
  552. for (int i = 0; i < strs.length; i++) {
  553. strs[i] = tempStrs[i];
  554. }
  555. return strs;
  556. }
  557. public static int[] spliteIntWithSpace(String source) {
  558. if (StringUtil.isEmpty(source)) {
  559. return null;
  560. }
  561. String[] strings = splitStringsWithSpace(source);
  562. int[] ints = new int[strings.length];
  563. for (int i = 0; i < strings.length; i++) {
  564. ints[i] = Integer.valueOf(strings[i]);
  565. }
  566. return ints;
  567. }
  568. /**
  569. * 定义size位整数,如果位数达不到,前面用0补齐
  570. * 如果超出位数,用规定位数最大数补齐
  571. * */
  572. public static String formatSizedNum(int num, int size) {
  573. String strNum = String.valueOf(num);
  574. if (strNum.length() < size) {
  575. while(strNum.length() < size) {
  576. strNum = "0" + strNum;
  577. }
  578. } else if (strNum.length() > size) {
  579. strNum = "";
  580. while(strNum.length() < size) {
  581. strNum += "9";
  582. }
  583. }
  584. return strNum;
  585. }
  586. /**
  587. * 用##分割
  588. */
  589. public static String[] spliteStringWithFS(String source) {
  590. if (StringUtil.isEmpty(source)) {
  591. return null;
  592. }
  593. String[] strs = source.split(FSpliter);
  594. return strs;
  595. }
  596. /**
  597. * 用||分割
  598. */
  599. public static String[] spliteStringWithSS(String source) {
  600. if (StringUtil.isEmpty(source)) {
  601. return null;
  602. }
  603. String[] strs = source.split(SSpliter);
  604. return strs;
  605. }
  606. public static boolean isSame(String source, String target) {
  607. if (source == null && target != null) {
  608. return false;
  609. } else if (source != null && target == null) {
  610. return false;
  611. } else if (source == target) {
  612. return true;
  613. } else if (source.equals(target)) {
  614. return true;
  615. } else {
  616. return false;
  617. }
  618. }
  619. public static String encryptionPhone(String phone) {
  620. StringBuilder builder = new StringBuilder(phone);
  621. if (phone.length() >= 11) {
  622. for (int i = 3; i < phone.length() - 4; i++) {
  623. builder.setCharAt(i, '*');
  624. }
  625. } else {
  626. for (int i = 2; i < phone.length() - 2; i++) {
  627. builder.setCharAt(i, '*');
  628. }
  629. }
  630. return builder.toString();
  631. }
  632. /**
  633. * 将字符串中的Unicode编码转换成UTF-8
  634. * */
  635. public static String decodeUnicode(String theString) {
  636. char aChar;
  637. int len = theString.length();
  638. StringBuffer outBuffer = new StringBuffer(len);
  639. for (int x = 0; x < len;) {
  640. aChar = theString.charAt(x++);
  641. if (aChar == '\\') {
  642. aChar = theString.charAt(x++);
  643. if (aChar == 'u') {
  644. // Read the xxxx
  645. int value = 0;
  646. for (int i = 0; i < 4; i++) {
  647. aChar = theString.charAt(x++);
  648. switch (aChar) {
  649. case '0':
  650. case '1':
  651. case '2':
  652. case '3':
  653. case '4':
  654. case '5':
  655. case '6':
  656. case '7':
  657. case '8':
  658. case '9':
  659. value = (value << 4) + aChar - '0';
  660. break;
  661. case 'a':
  662. case 'b':
  663. case 'c':
  664. case 'd':
  665. case 'e':
  666. case 'f':
  667. value = (value << 4) + 10 + aChar - 'a';
  668. break;
  669. case 'A':
  670. case 'B':
  671. case 'C':
  672. case 'D':
  673. case 'E':
  674. case 'F':
  675. value = (value << 4) + 10 + aChar - 'A';
  676. break;
  677. default:
  678. throw new IllegalArgumentException(
  679. "Malformed \\uxxxx encoding.");
  680. }
  681. }
  682. outBuffer.append((char) value);
  683. } else {
  684. if (aChar == 't')
  685. aChar = '\t';
  686. else if (aChar == 'r')
  687. aChar = '\r';
  688. else if (aChar == 'n')
  689. aChar = '\n';
  690. else if (aChar == 'f')
  691. aChar = '\f';
  692. outBuffer.append(aChar);
  693. }
  694. } else
  695. outBuffer.append(aChar);
  696. }
  697. return outBuffer.toString();
  698. }
  699. }