java常用工具类(一)

时间:2023-03-09 02:46:16
java常用工具类(一)

一、String工具类

  1. package com.mkyong.common;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. /**
  5. *
  6. * String工具类. <br>
  7. *
  8. * @author 宋立君
  9. * @date 2014年06月24日
  10. */
  11. public class StringUtil {
  12. private static final int INDEX_NOT_FOUND = -1;
  13. private static final String EMPTY = "";
  14. /**
  15. * <p>
  16. * The maximum size to which the padding constant(s) can expand.
  17. * </p>
  18. */
  19. private static final int PAD_LIMIT = 8192;
  20. /**
  21. * 功能:将半角的符号转换成全角符号.(即英文字符转中文字符)
  22. *
  23. * @author 宋立君
  24. * @param str
  25. *            源字符串
  26. * @return String
  27. * @date 2014年06月24日
  28. */
  29. public static String changeToFull(String str) {
  30. String source = "1234567890!@#$%^&*()abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_=+\\|[];:'\",<.>/?";
  31. String[] decode = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "0",
  32. "!", "@", "#", "$", "%", "︿", "&", "*", "(", ")", "a", "b",
  33. "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n",
  34. "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
  35. "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L",
  36. "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X",
  37. "Y", "Z", "-", "_", "=", "+", "\", "|", "【", "】", ";", ":",
  38. "'", "\"", ",", "〈", "。", "〉", "/", "?" };
  39. String result = "";
  40. for (int i = 0; i < str.length(); i++) {
  41. int pos = source.indexOf(str.charAt(i));
  42. if (pos != -1) {
  43. result += decode[pos];
  44. } else {
  45. result += str.charAt(i);
  46. }
  47. }
  48. return result;
  49. }
  50. /**
  51. * 功能:cs串中是否一个都不包含字符数组searchChars中的字符。
  52. *
  53. * @author 宋立君
  54. * @param cs
  55. *            字符串
  56. * @param searchChars
  57. *            字符数组
  58. * @return boolean 都不包含返回true,否则返回false。
  59. * @date 2014年06月24日
  60. */
  61. public static boolean containsNone(CharSequence cs, char... searchChars) {
  62. if (cs == null || searchChars == null) {
  63. return true;
  64. }
  65. int csLen = cs.length();
  66. int csLast = csLen - 1;
  67. int searchLen = searchChars.length;
  68. int searchLast = searchLen - 1;
  69. for (int i = 0; i < csLen; i++) {
  70. char ch = cs.charAt(i);
  71. for (int j = 0; j < searchLen; j++) {
  72. if (searchChars[j] == ch) {
  73. if (Character.isHighSurrogate(ch)) {
  74. if (j == searchLast) {
  75. // missing low surrogate, fine, like
  76. // String.indexOf(String)
  77. return false;
  78. }
  79. if (i < csLast
  80. && searchChars[j + 1] == cs.charAt(i + 1)) {
  81. return false;
  82. }
  83. } else {
  84. // ch is in the Basic Multilingual Plane
  85. return false;
  86. }
  87. }
  88. }
  89. }
  90. return true;
  91. }
  92. /**
  93. * <p>
  94. * 编码为Unicode,格式 '\u0020'.
  95. * </p>
  96. *
  97. * @author 宋立君
  98. *
  99. *         <pre>
  100. *   CharUtils.unicodeEscaped(' ') = "\u0020"
  101. *   CharUtils.unicodeEscaped('A') = "\u0041"
  102. * </pre>
  103. *
  104. * @param ch
  105. *            源字符串
  106. * @return 转码后的字符串
  107. * @date 2014年06月24日
  108. */
  109. public static String unicodeEscaped(char ch) {
  110. if (ch < 0x10) {
  111. return "\\u000" + Integer.toHexString(ch);
  112. } else if (ch < 0x100) {
  113. return "\\u00" + Integer.toHexString(ch);
  114. } else if (ch < 0x1000) {
  115. return "\\u0" + Integer.toHexString(ch);
  116. }
  117. return "\\u" + Integer.toHexString(ch);
  118. }
  119. /**
  120. * <p>
  121. * 进行tostring操作,如果传入的是null,返回空字符串。
  122. * </p>
  123. *
  124. * <pre>
  125. * ObjectUtils.toString(null)         = ""
  126. * ObjectUtils.toString("")           = ""
  127. * ObjectUtils.toString("bat")        = "bat"
  128. * ObjectUtils.toString(Boolean.TRUE) = "true"
  129. * </pre>
  130. *
  131. * @param obj
  132. *            源
  133. * @return String
  134. */
  135. public static String toString(Object obj) {
  136. return obj == null ? "" : obj.toString();
  137. }
  138. /**
  139. * <p>
  140. * 进行tostring操作,如果传入的是null,返回指定的默认值。
  141. * </p>
  142. *
  143. * <pre>
  144. * ObjectUtils.toString(null, null)           = null
  145. * ObjectUtils.toString(null, "null")         = "null"
  146. * ObjectUtils.toString("", "null")           = ""
  147. * ObjectUtils.toString("bat", "null")        = "bat"
  148. * ObjectUtils.toString(Boolean.TRUE, "null") = "true"
  149. * </pre>
  150. *
  151. * @param obj
  152. *            源
  153. * @param nullStr
  154. *            如果obj为null时返回这个指定值
  155. * @return String
  156. */
  157. public static String toString(Object obj, String nullStr) {
  158. return obj == null ? nullStr : obj.toString();
  159. }
  160. /**
  161. * <p>
  162. * 只从源字符串中移除指定开头子字符串.
  163. * </p>
  164. *
  165. * <pre>
  166. * StringUtil.removeStart(null, *)      = null
  167. * StringUtil.removeStart("", *)        = ""
  168. * StringUtil.removeStart(*, null)      = *
  169. * StringUtil.removeStart("www.domain.com", "www.")   = "domain.com"
  170. * StringUtil.removeStart("domain.com", "www.")       = "domain.com"
  171. * StringUtil.removeStart("www.domain.com", "domain") = "www.domain.com"
  172. * StringUtil.removeStart("abc", "")    = "abc"
  173. * </pre>
  174. *
  175. * @param str
  176. *            源字符串
  177. * @param remove
  178. *            将要被移除的子字符串
  179. * @return String
  180. */
  181. public static String removeStart(String str, String remove) {
  182. if (isEmpty(str) || isEmpty(remove)) {
  183. return str;
  184. }
  185. if (str.startsWith(remove)) {
  186. return str.substring(remove.length());
  187. }
  188. return str;
  189. }
  190. /**
  191. * <p>
  192. * 只从源字符串中移除指定结尾的子字符串.
  193. * </p>
  194. *
  195. * <pre>
  196. * StringUtil.removeEnd(null, *)      = null
  197. * StringUtil.removeEnd("", *)        = ""
  198. * StringUtil.removeEnd(*, null)      = *
  199. * StringUtil.removeEnd("www.domain.com", ".com.")  = "www.domain.com"
  200. * StringUtil.removeEnd("www.domain.com", ".com")   = "www.domain"
  201. * StringUtil.removeEnd("www.domain.com", "domain") = "www.domain.com"
  202. * StringUtil.removeEnd("abc", "")    = "abc"
  203. * </pre>
  204. *
  205. * @param str
  206. *            源字符串
  207. * @param remove
  208. *            将要被移除的子字符串
  209. * @return String
  210. */
  211. public static String removeEnd(String str, String remove) {
  212. if (isEmpty(str) || isEmpty(remove)) {
  213. return str;
  214. }
  215. if (str.endsWith(remove)) {
  216. return str.substring(0, str.length() - remove.length());
  217. }
  218. return str;
  219. }
  220. /**
  221. * <p>
  222. * 将一个字符串重复N次
  223. * </p>
  224. *
  225. * <pre>
  226. * StringUtil.repeat(null, 2) = null
  227. * StringUtil.repeat("", 0)   = ""
  228. * StringUtil.repeat("", 2)   = ""
  229. * StringUtil.repeat("a", 3)  = "aaa"
  230. * StringUtil.repeat("ab", 2) = "abab"
  231. * StringUtil.repeat("a", -2) = ""
  232. * </pre>
  233. *
  234. * @param str
  235. *            源字符串
  236. * @param repeat
  237. *            重复的次数
  238. * @return String
  239. */
  240. public static String repeat(String str, int repeat) {
  241. // Performance tuned for 2.0 (JDK1.4)
  242. if (str == null) {
  243. return null;
  244. }
  245. if (repeat <= 0) {
  246. return EMPTY;
  247. }
  248. int inputLength = str.length();
  249. if (repeat == 1 || inputLength == 0) {
  250. return str;
  251. }
  252. if (inputLength == 1 && repeat <= PAD_LIMIT) {
  253. return repeat(str.charAt(0), repeat);
  254. }
  255. int outputLength = inputLength * repeat;
  256. switch (inputLength) {
  257. case 1:
  258. return repeat(str.charAt(0), repeat);
  259. case 2:
  260. char ch0 = str.charAt(0);
  261. char ch1 = str.charAt(1);
  262. char[] output2 = new char[outputLength];
  263. for (int i = repeat * 2 - 2; i >= 0; i--, i--) {
  264. output2[i] = ch0;
  265. output2[i + 1] = ch1;
  266. }
  267. return new String(output2);
  268. default:
  269. StringBuilder buf = new StringBuilder(outputLength);
  270. for (int i = 0; i < repeat; i++) {
  271. buf.append(str);
  272. }
  273. return buf.toString();
  274. }
  275. }
  276. /**
  277. * <p>
  278. * 将一个字符串重复N次,并且中间加上指定的分隔符
  279. * </p>
  280. *
  281. * <pre>
  282. * StringUtil.repeat(null, null, 2) = null
  283. * StringUtil.repeat(null, "x", 2)  = null
  284. * StringUtil.repeat("", null, 0)   = ""
  285. * StringUtil.repeat("", "", 2)     = ""
  286. * StringUtil.repeat("", "x", 3)    = "xxx"
  287. * StringUtil.repeat("?", ", ", 3)  = "?, ?, ?"
  288. * </pre>
  289. *
  290. * @param str
  291. *            源字符串
  292. * @param separator
  293. *            分隔符
  294. * @param repeat
  295. *            重复次数
  296. * @return String
  297. */
  298. public static String repeat(String str, String separator, int repeat) {
  299. if (str == null || separator == null) {
  300. return repeat(str, repeat);
  301. } else {
  302. // given that repeat(String, int) is quite optimized, better to rely
  303. // on it than try and splice this into it
  304. String result = repeat(str + separator, repeat);
  305. return removeEnd(result, separator);
  306. }
  307. }
  308. /**
  309. * <p>
  310. * 将某个字符重复N次.
  311. * </p>
  312. *
  313. * @param ch
  314. *            某个字符
  315. * @param repeat
  316. *            重复次数
  317. * @return String
  318. */
  319. public static String repeat(char ch, int repeat) {
  320. char[] buf = new char[repeat];
  321. for (int i = repeat - 1; i >= 0; i--) {
  322. buf[i] = ch;
  323. }
  324. return new String(buf);
  325. }
  326. /**
  327. * <p>
  328. * 字符串长度达不到指定长度时,在字符串右边补指定的字符.
  329. * </p>
  330. *
  331. * <pre>
  332. * StringUtil.rightPad(null, *, *)     = null
  333. * StringUtil.rightPad("", 3, 'z')     = "zzz"
  334. * StringUtil.rightPad("bat", 3, 'z')  = "bat"
  335. * StringUtil.rightPad("bat", 5, 'z')  = "batzz"
  336. * StringUtil.rightPad("bat", 1, 'z')  = "bat"
  337. * StringUtil.rightPad("bat", -1, 'z') = "bat"
  338. * </pre>
  339. *
  340. * @param str
  341. *            源字符串
  342. * @param size
  343. *            指定的长度
  344. * @param padChar
  345. *            进行补充的字符
  346. * @return String
  347. */
  348. public static String rightPad(String str, int size, char padChar) {
  349. if (str == null) {
  350. return null;
  351. }
  352. int pads = size - str.length();
  353. if (pads <= 0) {
  354. return str; // returns original String when possible
  355. }
  356. if (pads > PAD_LIMIT) {
  357. return rightPad(str, size, String.valueOf(padChar));
  358. }
  359. return str.concat(repeat(padChar, pads));
  360. }
  361. /**
  362. * <p>
  363. * 扩大字符串长度,从左边补充指定字符
  364. * </p>
  365. *
  366. * <pre>
  367. * StringUtil.rightPad(null, *, *)      = null
  368. * StringUtil.rightPad("", 3, "z")      = "zzz"
  369. * StringUtil.rightPad("bat", 3, "yz")  = "bat"
  370. * StringUtil.rightPad("bat", 5, "yz")  = "batyz"
  371. * StringUtil.rightPad("bat", 8, "yz")  = "batyzyzy"
  372. * StringUtil.rightPad("bat", 1, "yz")  = "bat"
  373. * StringUtil.rightPad("bat", -1, "yz") = "bat"
  374. * StringUtil.rightPad("bat", 5, null)  = "bat  "
  375. * StringUtil.rightPad("bat", 5, "")    = "bat  "
  376. * </pre>
  377. *
  378. * @param str
  379. *            源字符串
  380. * @param size
  381. *            扩大后的长度
  382. * @param padStr
  383. *            在右边补充的字符串
  384. * @return String
  385. */
  386. public static String rightPad(String str, int size, String padStr) {
  387. if (str == null) {
  388. return null;
  389. }
  390. if (isEmpty(padStr)) {
  391. padStr = " ";
  392. }
  393. int padLen = padStr.length();
  394. int strLen = str.length();
  395. int pads = size - strLen;
  396. if (pads <= 0) {
  397. return str; // returns original String when possible
  398. }
  399. if (padLen == 1 && pads <= PAD_LIMIT) {
  400. return rightPad(str, size, padStr.charAt(0));
  401. }
  402. if (pads == padLen) {
  403. return str.concat(padStr);
  404. } else if (pads < padLen) {
  405. return str.concat(padStr.substring(0, pads));
  406. } else {
  407. char[] padding = new char[pads];
  408. char[] padChars = padStr.toCharArray();
  409. for (int i = 0; i < pads; i++) {
  410. padding[i] = padChars[i % padLen];
  411. }
  412. return str.concat(new String(padding));
  413. }
  414. }
  415. /**
  416. * <p>
  417. * 扩大字符串长度,从左边补充空格
  418. * </p>
  419. *
  420. * <pre>
  421. * StringUtil.leftPad(null, *)   = null
  422. * StringUtil.leftPad("", 3)     = "   "
  423. * StringUtil.leftPad("bat", 3)  = "bat"
  424. * StringUtil.leftPad("bat", 5)  = "  bat"
  425. * StringUtil.leftPad("bat", 1)  = "bat"
  426. * StringUtil.leftPad("bat", -1) = "bat"
  427. * </pre>
  428. *
  429. * @param str
  430. *            源字符串
  431. * @param size
  432. *            扩大后的长度
  433. * @return String
  434. */
  435. public static String leftPad(String str, int size) {
  436. return leftPad(str, size, ' ');
  437. }
  438. /**
  439. * <p>
  440. * 扩大字符串长度,从左边补充指定的字符
  441. * </p>
  442. *
  443. * <pre>
  444. * StringUtil.leftPad(null, *, *)     = null
  445. * StringUtil.leftPad("", 3, 'z')     = "zzz"
  446. * StringUtil.leftPad("bat", 3, 'z')  = "bat"
  447. * StringUtil.leftPad("bat", 5, 'z')  = "zzbat"
  448. * StringUtil.leftPad("bat", 1, 'z')  = "bat"
  449. * StringUtil.leftPad("bat", -1, 'z') = "bat"
  450. * </pre>
  451. *
  452. * @param str
  453. *            源字符串
  454. * @param size
  455. *            扩大后的长度
  456. * @param padStr
  457. *            补充的字符
  458. * @return String
  459. */
  460. public static String leftPad(String str, int size, char padChar) {
  461. if (str == null) {
  462. return null;
  463. }
  464. int pads = size - str.length();
  465. if (pads <= 0) {
  466. return str; // returns original String when possible
  467. }
  468. if (pads > PAD_LIMIT) {
  469. return leftPad(str, size, String.valueOf(padChar));
  470. }
  471. return repeat(padChar, pads).concat(str);
  472. }
  473. /**
  474. * <p>
  475. * 扩大字符串长度,从左边补充指定的字符
  476. * </p>
  477. *
  478. * <pre>
  479. * StringUtil.leftPad(null, *, *)      = null
  480. * StringUtil.leftPad("", 3, "z")      = "zzz"
  481. * StringUtil.leftPad("bat", 3, "yz")  = "bat"
  482. * StringUtil.leftPad("bat", 5, "yz")  = "yzbat"
  483. * StringUtil.leftPad("bat", 8, "yz")  = "yzyzybat"
  484. * StringUtil.leftPad("bat", 1, "yz")  = "bat"
  485. * StringUtil.leftPad("bat", -1, "yz") = "bat"
  486. * StringUtil.leftPad("bat", 5, null)  = "  bat"
  487. * StringUtil.leftPad("bat", 5, "")    = "  bat"
  488. * </pre>
  489. *
  490. * @param str
  491. *            源字符串
  492. * @param size
  493. *            扩大后的长度
  494. * @param padStr
  495. *            补充的字符串
  496. * @return String
  497. */
  498. public static String leftPad(String str, int size, String padStr) {
  499. if (str == null) {
  500. return null;
  501. }
  502. if (isEmpty(padStr)) {
  503. padStr = " ";
  504. }
  505. int padLen = padStr.length();
  506. int strLen = str.length();
  507. int pads = size - strLen;
  508. if (pads <= 0) {
  509. return str; // returns original String when possible
  510. }
  511. if (padLen == 1 && pads <= PAD_LIMIT) {
  512. return leftPad(str, size, padStr.charAt(0));
  513. }
  514. if (pads == padLen) {
  515. return padStr.concat(str);
  516. } else if (pads < padLen) {
  517. return padStr.substring(0, pads).concat(str);
  518. } else {
  519. char[] padding = new char[pads];
  520. char[] padChars = padStr.toCharArray();
  521. for (int i = 0; i < pads; i++) {
  522. padding[i] = padChars[i % padLen];
  523. }
  524. return new String(padding).concat(str);
  525. }
  526. }
  527. /**
  528. * <p>
  529. * 扩大字符串长度并将现在的字符串居中,被扩大部分用空格填充。
  530. * <p>
  531. *
  532. * <pre>
  533. * StringUtil.center(null, *)   = null
  534. * StringUtil.center("", 4)     = "    "
  535. * StringUtil.center("ab", -1)  = "ab"
  536. * StringUtil.center("ab", 4)   = " ab "
  537. * StringUtil.center("abcd", 2) = "abcd"
  538. * StringUtil.center("a", 4)    = " a  "
  539. * </pre>
  540. *
  541. * @param str
  542. *            源字符串
  543. * @param size
  544. *            扩大后的长度
  545. * @return String
  546. */
  547. public static String center(String str, int size) {
  548. return center(str, size, ' ');
  549. }
  550. /**
  551. * <p>
  552. * 将字符串长度修改为指定长度,并进行居中显示。
  553. * </p>
  554. *
  555. * <pre>
  556. * StringUtil.center(null, *, *)     = null
  557. * StringUtil.center("", 4, ' ')     = "    "
  558. * StringUtil.center("ab", -1, ' ')  = "ab"
  559. * StringUtil.center("ab", 4, ' ')   = " ab"
  560. * StringUtil.center("abcd", 2, ' ') = "abcd"
  561. * StringUtil.center("a", 4, ' ')    = " a  "
  562. * StringUtil.center("a", 4, 'y')    = "yayy"
  563. * </pre>
  564. *
  565. * @param str
  566. *            源字符串
  567. * @param size
  568. *            指定的长度
  569. * @param padStr
  570. *            长度不够时补充的字符串
  571. * @return String
  572. * @throws IllegalArgumentException
  573. *             如果被补充字符串为 null或者 empty
  574. */
  575. public static String center(String str, int size, char padChar) {
  576. if (str == null || size <= 0) {
  577. return str;
  578. }
  579. int strLen = str.length();
  580. int pads = size - strLen;
  581. if (pads <= 0) {
  582. return str;
  583. }
  584. str = leftPad(str, strLen + pads / 2, padChar);
  585. str = rightPad(str, size, padChar);
  586. return str;
  587. }
  588. /**
  589. * <p>
  590. * 将字符串长度修改为指定长度,并进行居中显示。
  591. * </p>
  592. *
  593. * <pre>
  594. * StringUtil.center(null, *, *)     = null
  595. * StringUtil.center("", 4, " ")     = "    "
  596. * StringUtil.center("ab", -1, " ")  = "ab"
  597. * StringUtil.center("ab", 4, " ")   = " ab"
  598. * StringUtil.center("abcd", 2, " ") = "abcd"
  599. * StringUtil.center("a", 4, " ")    = " a  "
  600. * StringUtil.center("a", 4, "yz")   = "yayz"
  601. * StringUtil.center("abc", 7, null) = "  abc  "
  602. * StringUtil.center("abc", 7, "")   = "  abc  "
  603. * </pre>
  604. *
  605. * @param str
  606. *            源字符串
  607. * @param size
  608. *            指定的长度
  609. * @param padStr
  610. *            长度不够时补充的字符串
  611. * @return String
  612. * @throws IllegalArgumentException
  613. *             如果被补充字符串为 null或者 empty
  614. */
  615. public static String center(String str, int size, String padStr) {
  616. if (str == null || size <= 0) {
  617. return str;
  618. }
  619. if (isEmpty(padStr)) {
  620. padStr = " ";
  621. }
  622. int strLen = str.length();
  623. int pads = size - strLen;
  624. if (pads <= 0) {
  625. return str;
  626. }
  627. str = leftPad(str, strLen + pads / 2, padStr);
  628. str = rightPad(str, size, padStr);
  629. return str;
  630. }
  631. /**
  632. * <p>
  633. * 检查字符串是否全部为小写.
  634. * </p>
  635. *
  636. * <pre>
  637. * StringUtil.isAllLowerCase(null)   = false
  638. * StringUtil.isAllLowerCase("")     = false
  639. * StringUtil.isAllLowerCase("  ")   = false
  640. * StringUtil.isAllLowerCase("abc")  = true
  641. * StringUtil.isAllLowerCase("abC") = false
  642. * </pre>
  643. *
  644. * @param cs
  645. *            源字符串
  646. * @return String
  647. */
  648. public static boolean isAllLowerCase(String cs) {
  649. if (cs == null || isEmpty(cs)) {
  650. return false;
  651. }
  652. int sz = cs.length();
  653. for (int i = 0; i < sz; i++) {
  654. if (Character.isLowerCase(cs.charAt(i)) == false) {
  655. return false;
  656. }
  657. }
  658. return true;
  659. }
  660. /**
  661. * <p>
  662. * 检查是否都是大写.
  663. * </p>
  664. *
  665. * <pre>
  666. * StringUtil.isAllUpperCase(null)   = false
  667. * StringUtil.isAllUpperCase("")     = false
  668. * StringUtil.isAllUpperCase("  ")   = false
  669. * StringUtil.isAllUpperCase("ABC")  = true
  670. * StringUtil.isAllUpperCase("aBC") = false
  671. * </pre>
  672. *
  673. * @param cs
  674. *            源字符串
  675. * @return String
  676. */
  677. public static boolean isAllUpperCase(String cs) {
  678. if (cs == null || StringUtil.isEmpty(cs)) {
  679. return false;
  680. }
  681. int sz = cs.length();
  682. for (int i = 0; i < sz; i++) {
  683. if (Character.isUpperCase(cs.charAt(i)) == false) {
  684. return false;
  685. }
  686. }
  687. return true;
  688. }
  689. /**
  690. * <p>
  691. * 反转字符串.
  692. * </p>
  693. *
  694. * <pre>
  695. * StringUtil.reverse(null)  = null
  696. * StringUtil.reverse("")    = ""
  697. * StringUtil.reverse("bat") = "tab"
  698. * </pre>
  699. *
  700. * @param str
  701. *            源字符串
  702. * @return String
  703. */
  704. public static String reverse(String str) {
  705. if (str == null) {
  706. return null;
  707. }
  708. return new StringBuilder(str).reverse().toString();
  709. }
  710. /**
  711. * <p>
  712. * 字符串达不到一定长度时在右边补空白.
  713. * </p>
  714. *
  715. * <pre>
  716. * StringUtil.rightPad(null, *)   = null
  717. * StringUtil.rightPad("", 3)     = "   "
  718. * StringUtil.rightPad("bat", 3)  = "bat"
  719. * StringUtil.rightPad("bat", 5)  = "bat  "
  720. * StringUtil.rightPad("bat", 1)  = "bat"
  721. * StringUtil.rightPad("bat", -1) = "bat"
  722. * </pre>
  723. *
  724. * @param str
  725. *            源字符串
  726. * @param size
  727. *            指定的长度
  728. * @return String
  729. */
  730. public static String rightPad(String str, int size) {
  731. return rightPad(str, size, ' ');
  732. }
  733. /**
  734. * 从右边截取字符串.</p>
  735. *
  736. * <pre>
  737. * StringUtil.right(null, *)    = null
  738. * StringUtil.right(*, -ve)     = ""
  739. * StringUtil.right("", *)      = ""
  740. * StringUtil.right("abc", 0)   = ""
  741. * StringUtil.right("abc", 2)   = "bc"
  742. * StringUtil.right("abc", 4)   = "abc"
  743. * </pre>
  744. *
  745. * @param str
  746. *            源字符串
  747. * @param len
  748. *            长度
  749. * @return String
  750. */
  751. public static String right(String str, int len) {
  752. if (str == null) {
  753. return null;
  754. }
  755. if (len < 0) {
  756. return EMPTY;
  757. }
  758. if (str.length() <= len) {
  759. return str;
  760. }
  761. return str.substring(str.length() - len);
  762. }
  763. /**
  764. * <p>
  765. * 截取一个字符串的前几个.
  766. * </p>
  767. *
  768. * <pre>
  769. * StringUtil.left(null, *)    = null
  770. * StringUtil.left(*, -ve)     = ""
  771. * StringUtil.left("", *)      = ""
  772. * StringUtil.left("abc", 0)   = ""
  773. * StringUtil.left("abc", 2)   = "ab"
  774. * StringUtil.left("abc", 4)   = "abc"
  775. * </pre>
  776. *
  777. * @param str
  778. *            源字符串
  779. * @param len
  780. *            截取的长度
  781. * @return the String
  782. */
  783. public static String left(String str, int len) {
  784. if (str == null) {
  785. return null;
  786. }
  787. if (len < 0) {
  788. return EMPTY;
  789. }
  790. if (str.length() <= len) {
  791. return str;
  792. }
  793. return str.substring(0, len);
  794. }
  795. /**
  796. * <p>
  797. * 得到tag字符串中间的子字符串,只返回第一个匹配项。
  798. * </p>
  799. *
  800. * <pre>
  801. * StringUtil.substringBetween(null, *)            = null
  802. * StringUtil.substringBetween("", "")             = ""
  803. * StringUtil.substringBetween("", "tag")          = null
  804. * StringUtil.substringBetween("tagabctag", null)  = null
  805. * StringUtil.substringBetween("tagabctag", "")    = ""
  806. * StringUtil.substringBetween("tagabctag", "tag") = "abc"
  807. * </pre>
  808. *
  809. * @param str
  810. *            源字符串。
  811. * @param tag
  812. *            标识字符串。
  813. * @return String 子字符串, 如果没有符合要求的,返回{@code null}。
  814. */
  815. public static String substringBetween(String str, String tag) {
  816. return substringBetween(str, tag, tag);
  817. }
  818. /**
  819. * <p>
  820. * 得到两个字符串中间的子字符串,只返回第一个匹配项。
  821. * </p>
  822. *
  823. * <pre>
  824. * StringUtil.substringBetween("wx[b]yz", "[", "]") = "b"
  825. * StringUtil.substringBetween(null, *, *)          = null
  826. * StringUtil.substringBetween(*, null, *)          = null
  827. * StringUtil.substringBetween(*, *, null)          = null
  828. * StringUtil.substringBetween("", "", "")          = ""
  829. * StringUtil.substringBetween("", "", "]")         = null
  830. * StringUtil.substringBetween("", "[", "]")        = null
  831. * StringUtil.substringBetween("yabcz", "", "")     = ""
  832. * StringUtil.substringBetween("yabcz", "y", "z")   = "abc"
  833. * StringUtil.substringBetween("yabczyabcz", "y", "z")   = "abc"
  834. * </pre>
  835. *
  836. * @param str
  837. *            源字符串
  838. * @param open
  839. *            起字符串。
  840. * @param close
  841. *            末字符串。
  842. * @return String 子字符串, 如果没有符合要求的,返回{@code null}。
  843. */
  844. public static String substringBetween(String str, String open, String close) {
  845. if (str == null || open == null || close == null) {
  846. return null;
  847. }
  848. int start = str.indexOf(open);
  849. if (start != INDEX_NOT_FOUND) {
  850. int end = str.indexOf(close, start + open.length());
  851. if (end != INDEX_NOT_FOUND) {
  852. return str.substring(start + open.length(), end);
  853. }
  854. }
  855. return null;
  856. }
  857. /**
  858. * <p>
  859. * 得到两个字符串中间的子字符串,所有匹配项组合为数组并返回。
  860. * </p>
  861. *
  862. * <pre>
  863. * StringUtil.substringsBetween("[a][b][c]", "[", "]") = ["a","b","c"]
  864. * StringUtil.substringsBetween(null, *, *)            = null
  865. * StringUtil.substringsBetween(*, null, *)            = null
  866. * StringUtil.substringsBetween(*, *, null)            = null
  867. * StringUtil.substringsBetween("", "[", "]")          = []
  868. * </pre>
  869. *
  870. * @param str
  871. *            源字符串
  872. * @param open
  873. *            起字符串。
  874. * @param close
  875. *            末字符串。
  876. * @return String 子字符串数组, 如果没有符合要求的,返回{@code null}。
  877. */
  878. public static String[] substringsBetween(String str, String open,
  879. String close) {
  880. if (str == null || isEmpty(open) || isEmpty(close)) {
  881. return null;
  882. }
  883. int strLen = str.length();
  884. if (strLen == 0) {
  885. return new String[0];
  886. }
  887. int closeLen = close.length();
  888. int openLen = open.length();
  889. List<String> list = new ArrayList<String>();
  890. int pos = 0;
  891. while (pos < strLen - closeLen) {
  892. int start = str.indexOf(open, pos);
  893. if (start < 0) {
  894. break;
  895. }
  896. start += openLen;
  897. int end = str.indexOf(close, start);
  898. if (end < 0) {
  899. break;
  900. }
  901. list.add(str.substring(start, end));
  902. pos = end + closeLen;
  903. }
  904. if (list.isEmpty()) {
  905. return null;
  906. }
  907. return list.toArray(new String[list.size()]);
  908. }
  909. /**
  910. * 功能:切换字符串中的所有字母大小写。<br/>
  911. *
  912. * <pre>
  913. * StringUtil.swapCase(null)                 = null
  914. * StringUtil.swapCase("")                   = ""
  915. * StringUtil.swapCase("The dog has a BONE") = "tHE DOG HAS A bone"
  916. * </pre>
  917. *
  918. *
  919. * @param str
  920. *            源字符串
  921. * @return String
  922. */
  923. public static String swapCase(String str) {
  924. if (StringUtil.isEmpty(str)) {
  925. return str;
  926. }
  927. char[] buffer = str.toCharArray();
  928. boolean whitespace = true;
  929. for (int i = 0; i < buffer.length; i++) {
  930. char ch = buffer[i];
  931. if (Character.isUpperCase(ch)) {
  932. buffer[i] = Character.toLowerCase(ch);
  933. whitespace = false;
  934. } else if (Character.isTitleCase(ch)) {
  935. buffer[i] = Character.toLowerCase(ch);
  936. whitespace = false;
  937. } else if (Character.isLowerCase(ch)) {
  938. if (whitespace) {
  939. buffer[i] = Character.toTitleCase(ch);
  940. whitespace = false;
  941. } else {
  942. buffer[i] = Character.toUpperCase(ch);
  943. }
  944. } else {
  945. whitespace = Character.isWhitespace(ch);
  946. }
  947. }
  948. return new String(buffer);
  949. }
  950. /**
  951. * 功能:截取出最后一个标志位之后的字符串.<br/>
  952. * 如果sourceStr为empty或者expr为null,直接返回源字符串。<br/>
  953. * 如果expr长度为0,直接返回sourceStr。<br/>
  954. * 如果expr在sourceStr中不存在,直接返回sourceStr。<br/>
  955. *
  956. * @author 宋立君
  957. * @date 2014年06月24日
  958. * @param sourceStr
  959. *            被截取的字符串
  960. * @param expr
  961. *            分隔符
  962. * @return String
  963. */
  964. public static String substringAfterLast(String sourceStr, String expr) {
  965. if (isEmpty(sourceStr) || expr == null) {
  966. return sourceStr;
  967. }
  968. if (expr.length() == 0) {
  969. return sourceStr;
  970. }
  971. int pos = sourceStr.lastIndexOf(expr);
  972. if (pos == -1) {
  973. return sourceStr;
  974. }
  975. return sourceStr.substring(pos + expr.length());
  976. }
  977. /**
  978. * 功能:截取出最后一个标志位之前的字符串.<br/>
  979. * 如果sourceStr为empty或者expr为null,直接返回源字符串。<br/>
  980. * 如果expr长度为0,直接返回sourceStr。<br/>
  981. * 如果expr在sourceStr中不存在,直接返回sourceStr。<br/>
  982. *
  983. * @author 宋立君
  984. * @date 2014年06月24日
  985. * @param sourceStr
  986. *            被截取的字符串
  987. * @param expr
  988. *            分隔符
  989. * @return String
  990. */
  991. public static String substringBeforeLast(String sourceStr, String expr) {
  992. if (isEmpty(sourceStr) || expr == null) {
  993. return sourceStr;
  994. }
  995. if (expr.length() == 0) {
  996. return sourceStr;
  997. }
  998. int pos = sourceStr.lastIndexOf(expr);
  999. if (pos == -1) {
  1000. return sourceStr;
  1001. }
  1002. return sourceStr.substring(0, pos);
  1003. }
  1004. /**
  1005. * 功能:截取出第一个标志位之后的字符串.<br/>
  1006. * 如果sourceStr为empty或者expr为null,直接返回源字符串。<br/>
  1007. * 如果expr长度为0,直接返回sourceStr。<br/>
  1008. * 如果expr在sourceStr中不存在,直接返回sourceStr。<br/>
  1009. *
  1010. * @author 宋立君
  1011. * @date 2014年06月24日
  1012. * @param sourceStr
  1013. *            被截取的字符串
  1014. * @param expr
  1015. *            分隔符
  1016. * @return String
  1017. */
  1018. public static String substringAfter(String sourceStr, String expr) {
  1019. if (isEmpty(sourceStr) || expr == null) {
  1020. return sourceStr;
  1021. }
  1022. if (expr.length() == 0) {
  1023. return sourceStr;
  1024. }
  1025. int pos = sourceStr.indexOf(expr);
  1026. if (pos == -1) {
  1027. return sourceStr;
  1028. }
  1029. return sourceStr.substring(pos + expr.length());
  1030. }
  1031. /**
  1032. * 功能:截取出第一个标志位之前的字符串.<br/>
  1033. * 如果sourceStr为empty或者expr为null,直接返回源字符串。<br/>
  1034. * 如果expr长度为0,直接返回sourceStr。<br/>
  1035. * 如果expr在sourceStr中不存在,直接返回sourceStr。<br/>
  1036. * 如果expr在sourceStr中存在不止一个,以第一个位置为准。
  1037. *
  1038. * @author 宋立君
  1039. * @date 2014年06月24日
  1040. * @param sourceStr
  1041. *            被截取的字符串
  1042. * @param expr
  1043. *            分隔符
  1044. * @return String
  1045. */
  1046. public static String substringBefore(String sourceStr, String expr) {
  1047. if (isEmpty(sourceStr) || expr == null) {
  1048. return sourceStr;
  1049. }
  1050. if (expr.length() == 0) {
  1051. return sourceStr;
  1052. }
  1053. int pos = sourceStr.indexOf(expr);
  1054. if (pos == -1) {
  1055. return sourceStr;
  1056. }
  1057. return sourceStr.substring(0, pos);
  1058. }
  1059. /**
  1060. * 功能:检查这个字符串是不是空字符串。<br/>
  1061. * 如果这个字符串为null或者trim后为空字符串则返回true,否则返回false。
  1062. *
  1063. * @author 宋立君
  1064. * @date 2014年06月24日
  1065. * @param chkStr
  1066. *            被检查的字符串
  1067. * @return boolean
  1068. */
  1069. public static boolean isEmpty(String chkStr) {
  1070. if (chkStr == null) {
  1071. return true;
  1072. } else {
  1073. return "".equals(chkStr.trim()) ? true : false;
  1074. }
  1075. }
  1076. /**
  1077. * 如果字符串没有超过最长显示长度返回原字符串,否则从开头截取指定长度并加...返回。
  1078. *
  1079. * @param str
  1080. *            原字符串
  1081. * @param length
  1082. *            字符串最长显示的长度
  1083. * @return 转换后的字符串
  1084. */
  1085. public static String trimString(String str, int length) {
  1086. if (str == null) {
  1087. return "";
  1088. } else if (str.length() > length) {
  1089. return str.substring(0, length - 3) + "...";
  1090. } else {
  1091. return str;
  1092. }
  1093. }
  1094. }

二、MD5

  1. package com.mkyong.common;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.IOException;
  5. import java.nio.MappedByteBuffer;
  6. import java.nio.channels.FileChannel;
  7. import java.security.MessageDigest;
  8. import java.security.NoSuchAlgorithmException;
  9. /**
  10. *
  11. * String工具类. <br>
  12. *
  13. * @author 宋立君
  14. * @date 2014年06月24日
  15. */
  16. public class MD5Util {
  17. protected static char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6',
  18. '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
  19. protected static MessageDigest messagedigest = null;
  20. static {
  21. try {
  22. messagedigest = MessageDigest.getInstance("MD5");
  23. } catch (NoSuchAlgorithmException nsaex) {
  24. System.err.println(MD5Util.class.getName()
  25. + "初始化失败,MessageDigest不支持MD5Util。");
  26. nsaex.printStackTrace();
  27. }
  28. }
  29. /**
  30. * 功能:加盐版的MD5.返回格式为MD5(密码+{盐值})
  31. *
  32. * @author 宋立君
  33. * @date 2014年06月24日
  34. * @param password
  35. *            密码
  36. * @param salt
  37. *            盐值
  38. * @return String
  39. */
  40. public static String getMD5StringWithSalt(String password, String salt) {
  41. if (password == null) {
  42. throw new IllegalArgumentException("password不能为null");
  43. }
  44. if (StringUtil.isEmpty(salt)) {
  45. throw new IllegalArgumentException("salt不能为空");
  46. }
  47. if ((salt.toString().lastIndexOf("{") != -1)
  48. || (salt.toString().lastIndexOf("}") != -1)) {
  49. throw new IllegalArgumentException("salt中不能包含 { 或者 }");
  50. }
  51. return getMD5String(password + "{" + salt.toString() + "}");
  52. }
  53. /**
  54. * 功能:得到文件的md5值。
  55. *
  56. * @author 宋立君
  57. * @date 2014年06月24日
  58. * @param file
  59. *            文件。
  60. * @return String
  61. * @throws IOException
  62. *             读取文件IO异常时。
  63. */
  64. public static String getFileMD5String(File file) throws IOException {
  65. FileInputStream in = new FileInputStream(file);
  66. FileChannel ch = in.getChannel();
  67. MappedByteBuffer byteBuffer = ch.map(FileChannel.MapMode.READ_ONLY, 0,
  68. file.length());
  69. messagedigest.update(byteBuffer);
  70. return bufferToHex(messagedigest.digest());
  71. }
  72. /**
  73. * 功能:得到一个字符串的MD5值。
  74. *
  75. * @author 宋立君
  76. * @date 2014年06月24日
  77. * @param str
  78. *            字符串
  79. * @return String
  80. */
  81. public static String getMD5String(String str) {
  82. return getMD5String(str.getBytes());
  83. }
  84. private static String getMD5String(byte[] bytes) {
  85. messagedigest.update(bytes);
  86. return bufferToHex(messagedigest.digest());
  87. }
  88. private static String bufferToHex(byte bytes[]) {
  89. return bufferToHex(bytes, 0, bytes.length);
  90. }
  91. private static String bufferToHex(byte bytes[], int m, int n) {
  92. StringBuffer stringbuffer = new StringBuffer(2 * n);
  93. int k = m + n;
  94. for (int l = m; l < k; l++) {
  95. appendHexPair(bytes[l], stringbuffer);
  96. }
  97. return stringbuffer.toString();
  98. }
  99. private static void appendHexPair(byte bt, StringBuffer stringbuffer) {
  100. char c0 = hexDigits[(bt & 0xf0) >> 4];
  101. char c1 = hexDigits[bt & 0xf];
  102. stringbuffer.append(c0);
  103. stringbuffer.append(c1);
  104. }
  105. }

三、File工具类

  1. package com.mkyong.common;
  2. import java.io.ByteArrayInputStream;
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. import java.io.FileOutputStream;
  6. import java.io.IOException;
  7. import java.io.InputStream;
  8. import java.io.OutputStream;
  9. /**
  10. * 文件相关操作辅助类。
  11. *
  12. * @author 宋立君
  13. * @date 2014年06月24日
  14. */
  15. public class FileUtil {
  16. private static final String FOLDER_SEPARATOR = "/";
  17. private static final char EXTENSION_SEPARATOR = '.';
  18. /**
  19. * 功能:复制文件或者文件夹。
  20. *
  21. * @author 宋立君
  22. * @date 2014年06月24日
  23. * @param inputFile
  24. *            源文件
  25. * @param outputFile
  26. *            目的文件
  27. * @param isOverWrite
  28. *            是否覆盖(只针对文件)
  29. * @throws IOException
  30. */
  31. public static void copy(File inputFile, File outputFile, boolean isOverWrite)
  32. throws IOException {
  33. if (!inputFile.exists()) {
  34. throw new RuntimeException(inputFile.getPath() + "源目录不存在!");
  35. }
  36. copyPri(inputFile, outputFile, isOverWrite);
  37. }
  38. /**
  39. * 功能:为copy 做递归使用。
  40. *
  41. * @author 宋立君
  42. * @date 2014年06月24日
  43. * @param inputFile
  44. * @param outputFile
  45. * @param isOverWrite
  46. * @throws IOException
  47. */
  48. private static void copyPri(File inputFile, File outputFile,
  49. boolean isOverWrite) throws IOException {
  50. // 是个文件。
  51. if (inputFile.isFile()) {
  52. copySimpleFile(inputFile, outputFile, isOverWrite);
  53. } else {
  54. // 文件夹
  55. if (!outputFile.exists()) {
  56. outputFile.mkdir();
  57. }
  58. // 循环子文件夹
  59. for (File child : inputFile.listFiles()) {
  60. copy(child,
  61. new File(outputFile.getPath() + "/" + child.getName()),
  62. isOverWrite);
  63. }
  64. }
  65. }
  66. /**
  67. * 功能:copy单个文件
  68. *
  69. * @author 宋立君
  70. * @date 2014年06月24日
  71. * @param inputFile
  72. *            源文件
  73. * @param outputFile
  74. *            目标文件
  75. * @param isOverWrite
  76. *            是否允许覆盖
  77. * @throws IOException
  78. */
  79. private static void copySimpleFile(File inputFile, File outputFile,
  80. boolean isOverWrite) throws IOException {
  81. // 目标文件已经存在
  82. if (outputFile.exists()) {
  83. if (isOverWrite) {
  84. if (!outputFile.delete()) {
  85. throw new RuntimeException(outputFile.getPath() + "无法覆盖!");
  86. }
  87. } else {
  88. // 不允许覆盖
  89. return;
  90. }
  91. }
  92. InputStream in = new FileInputStream(inputFile);
  93. OutputStream out = new FileOutputStream(outputFile);
  94. byte[] buffer = new byte[1024];
  95. int read = 0;
  96. while ((read = in.read(buffer)) != -1) {
  97. out.write(buffer, 0, read);
  98. }
  99. in.close();
  100. out.close();
  101. }
  102. /**
  103. * 功能:删除文件
  104. *
  105. * @author 宋立君
  106. * @date 2014年06月24日
  107. * @param file
  108. *            文件
  109. */
  110. public static void delete(File file) {
  111. deleteFile(file);
  112. }
  113. /**
  114. * 功能:删除文件,内部递归使用
  115. *
  116. * @author 宋立君
  117. * @date 2014年06月24日
  118. * @param file
  119. *            文件
  120. * @return boolean true 删除成功,false 删除失败。
  121. */
  122. private static void deleteFile(File file) {
  123. if (file == null || !file.exists()) {
  124. return;
  125. }
  126. // 单文件
  127. if (!file.isDirectory()) {
  128. boolean delFlag = file.delete();
  129. if (!delFlag) {
  130. throw new RuntimeException(file.getPath() + "删除失败!");
  131. } else {
  132. return;
  133. }
  134. }
  135. // 删除子目录
  136. for (File child : file.listFiles()) {
  137. deleteFile(child);
  138. }
  139. // 删除自己
  140. file.delete();
  141. }
  142. /**
  143. * 从文件路径中抽取文件的扩展名, 例如. "mypath/myfile.txt" -> "txt". * @author 宋立君
  144. *
  145. * @date 2014年06月24日
  146. * @param 文件路径
  147. * @return 如果path为null,直接返回null。
  148. */
  149. public static String getFilenameExtension(String path) {
  150. if (path == null) {
  151. return null;
  152. }
  153. int extIndex = path.lastIndexOf(EXTENSION_SEPARATOR);
  154. if (extIndex == -1) {
  155. return null;
  156. }
  157. int folderIndex = path.lastIndexOf(FOLDER_SEPARATOR);
  158. if (folderIndex > extIndex) {
  159. return null;
  160. }
  161. return path.substring(extIndex + 1);
  162. }
  163. /**
  164. * 从文件路径中抽取文件名, 例如: "mypath/myfile.txt" -> "myfile.txt"。 * @author 宋立君
  165. *
  166. * @date 2014年06月24日
  167. * @param path
  168. *            文件路径。
  169. * @return 抽取出来的文件名, 如果path为null,直接返回null。
  170. */
  171. public static String getFilename(String path) {
  172. if (path == null) {
  173. return null;
  174. }
  175. int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR);
  176. return (separatorIndex != -1 ? path.substring(separatorIndex + 1)
  177. : path);
  178. }
  179. /**
  180. * 功能:保存文件。
  181. *
  182. * @author 宋立君
  183. * @date 2014年06月24日
  184. * @param content
  185. *            字节
  186. * @param file
  187. *            保存到的文件
  188. * @throws IOException
  189. */
  190. public static void save(byte[] content, File file) throws IOException {
  191. if (file == null) {
  192. throw new RuntimeException("保存文件不能为空");
  193. }
  194. if (content == null) {
  195. throw new RuntimeException("文件流不能为空");
  196. }
  197. InputStream is = new ByteArrayInputStream(content);
  198. save(is, file);
  199. }
  200. /**
  201. * 功能:保存文件
  202. *
  203. * @author 宋立君
  204. * @date 2014年06月24日
  205. * @param streamIn
  206. *            文件流
  207. * @param file
  208. *            保存到的文件
  209. * @throws IOException
  210. */
  211. public static void save(InputStream streamIn, File file) throws IOException {
  212. if (file == null) {
  213. throw new RuntimeException("保存文件不能为空");
  214. }
  215. if (streamIn == null) {
  216. throw new RuntimeException("文件流不能为空");
  217. }
  218. // 输出流
  219. OutputStream streamOut = null;
  220. // 文件夹不存在就创建。
  221. if (!file.getParentFile().exists()) {
  222. file.getParentFile().mkdirs();
  223. }
  224. streamOut = new FileOutputStream(file);
  225. int bytesRead = 0;
  226. byte[] buffer = new byte[8192];
  227. while ((bytesRead = streamIn.read(buffer, 0, 8192)) != -1) {
  228. streamOut.write(buffer, 0, bytesRead);
  229. }
  230. streamOut.close();
  231. streamIn.close();
  232. }
  233. }