IP地址获取

  1. public class IPUtil {
  2.  
  3. private static final String UNKNOWN = "unknown";
  4.  
  5. protected IPUtil(){
  6.  
  7. }
  8.  
  9. /**
  10. * 获取 IP地址
  11. * 使用 Nginx等反向代理软件, 则不能通过 request.getRemoteAddr()获取 IP地址
  12. * 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,
  13. * X-Forwarded-For中第一个非 unknown的有效IP字符串,则为真实IP地址
  14. */
  15. public static String getIpAddr(HttpServletRequest request) {
  16. String ip = request.getHeader("x-forwarded-for");
  17. if (StringUtils.isNotEmpty(ip)) {
  18. ip = ip.split(", ")[0];
  19. }
  20. if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
  21. ip = request.getHeader("Proxy-Client-IP");
  22. }
  23. if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
  24. ip = request.getHeader("WL-Proxy-Client-IP");
  25. }
  26. if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
  27. ip = request.getRemoteAddr();
  28. }
  29. return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
  30. }
  31.  
  32. }

获取上个月月份字符串

  1. public static final String getLastMonth() {
  2. SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
  3. Date date = new Date();
  4. Calendar calendar = Calendar.getInstance();
  5. // 设置为当前时间
  6. calendar.setTime(date);
  7. // 设置为上一个月
  8. calendar.add(Calendar.MONTH,-1);
  9. date = calendar.getTime();
  10. return format.format(date);
  11. }

日期工具类

  1. /**
  2. * 日期工具类
  3. *
  4. */
  5. @UtilityClass
  6. public class DateUtil {
  7.  
  8. public static final String PATTERN_DATETIME = "yyyy-MM-dd HH:mm:ss";
  9. public static final String PATTERN_DATETIME_MINI = "yyyyMMddHHmmss";
  10. public static final String PATTERN_DATE = "yyyy-MM-dd";
  11. public static final String PATTERN_TIME = "HH:mm:ss";
  12. /**
  13. * 老 date 格式化
  14. */
  15. public static final ConcurrentDateFormat DATETIME_FORMAT = ConcurrentDateFormat.of(PATTERN_DATETIME);
  16. public static final ConcurrentDateFormat DATETIME_MINI_FORMAT = ConcurrentDateFormat.of(PATTERN_DATETIME_MINI);
  17. public static final ConcurrentDateFormat DATE_FORMAT = ConcurrentDateFormat.of(PATTERN_DATE);
  18. public static final ConcurrentDateFormat TIME_FORMAT = ConcurrentDateFormat.of(PATTERN_TIME);
  19. /**
  20. * java 8 时间格式化
  21. */
  22. public static final DateTimeFormatter DATETIME_FORMATTER = DateTimeFormatter.ofPattern(DateUtil.PATTERN_DATETIME);
  23. public static final DateTimeFormatter DATETIME_MINI_FORMATTER = DateTimeFormatter.ofPattern(DateUtil.PATTERN_DATETIME_MINI);
  24. public static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern(DateUtil.PATTERN_DATE);
  25. public static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern(DateUtil.PATTERN_TIME);
  26.  
  27. /**
  28. * 获取当前日期
  29. *
  30. * @return 当前日期
  31. */
  32. public static Date now() {
  33. return new Date();
  34. }
  35.  
  36. /**
  37. * 添加年
  38. *
  39. * @param date 时间
  40. * @param yearsToAdd 添加的年数
  41. * @return 设置后的时间
  42. */
  43. public static Date plusYears(Date date, int yearsToAdd) {
  44. return DateUtil.set(date, Calendar.YEAR, yearsToAdd);
  45. }
  46.  
  47. /**
  48. * 添加月
  49. *
  50. * @param date 时间
  51. * @param monthsToAdd 添加的月数
  52. * @return 设置后的时间
  53. */
  54. public static Date plusMonths(Date date, int monthsToAdd) {
  55. return DateUtil.set(date, Calendar.MONTH, monthsToAdd);
  56. }
  57.  
  58. /**
  59. * 添加周
  60. *
  61. * @param date 时间
  62. * @param weeksToAdd 添加的周数
  63. * @return 设置后的时间
  64. */
  65. public static Date plusWeeks(Date date, int weeksToAdd) {
  66. return DateUtil.plus(date, Period.ofWeeks(weeksToAdd));
  67. }
  68.  
  69. /**
  70. * 添加天
  71. *
  72. * @param date 时间
  73. * @param daysToAdd 添加的天数
  74. * @return 设置后的时间
  75. */
  76. public static Date plusDays(Date date, long daysToAdd) {
  77. return DateUtil.plus(date, Duration.ofDays(daysToAdd));
  78. }
  79.  
  80. /**
  81. * 添加小时
  82. *
  83. * @param date 时间
  84. * @param hoursToAdd 添加的小时数
  85. * @return 设置后的时间
  86. */
  87. public static Date plusHours(Date date, long hoursToAdd) {
  88. return DateUtil.plus(date, Duration.ofHours(hoursToAdd));
  89. }
  90.  
  91. /**
  92. * 添加分钟
  93. *
  94. * @param date 时间
  95. * @param minutesToAdd 添加的分钟数
  96. * @return 设置后的时间
  97. */
  98. public static Date plusMinutes(Date date, long minutesToAdd) {
  99. return DateUtil.plus(date, Duration.ofMinutes(minutesToAdd));
  100. }
  101.  
  102. /**
  103. * 添加秒
  104. *
  105. * @param date 时间
  106. * @param secondsToAdd 添加的秒数
  107. * @return 设置后的时间
  108. */
  109. public static Date plusSeconds(Date date, long secondsToAdd) {
  110. return DateUtil.plus(date, Duration.ofSeconds(secondsToAdd));
  111. }
  112.  
  113. /**
  114. * 添加毫秒
  115. *
  116. * @param date 时间
  117. * @param millisToAdd 添加的毫秒数
  118. * @return 设置后的时间
  119. */
  120. public static Date plusMillis(Date date, long millisToAdd) {
  121. return DateUtil.plus(date, Duration.ofMillis(millisToAdd));
  122. }
  123.  
  124. /**
  125. * 添加纳秒
  126. *
  127. * @param date 时间
  128. * @param nanosToAdd 添加的纳秒数
  129. * @return 设置后的时间
  130. */
  131. public static Date plusNanos(Date date, long nanosToAdd) {
  132. return DateUtil.plus(date, Duration.ofNanos(nanosToAdd));
  133. }
  134.  
  135. /**
  136. * 日期添加时间量
  137. *
  138. * @param date 时间
  139. * @param amount 时间量
  140. * @return 设置后的时间
  141. */
  142. public static Date plus(Date date, TemporalAmount amount) {
  143. Instant instant = date.toInstant();
  144. return Date.from(instant.plus(amount));
  145. }
  146.  
  147. /**
  148. * 减少年
  149. *
  150. * @param date 时间
  151. * @param years 减少的年数
  152. * @return 设置后的时间
  153. */
  154. public static Date minusYears(Date date, int years) {
  155. return DateUtil.set(date, Calendar.YEAR, -years);
  156. }
  157.  
  158. /**
  159. * 减少月
  160. *
  161. * @param date 时间
  162. * @param months 减少的月数
  163. * @return 设置后的时间
  164. */
  165. public static Date minusMonths(Date date, int months) {
  166. return DateUtil.set(date, Calendar.MONTH, -months);
  167. }
  168.  
  169. /**
  170. * 减少周
  171. *
  172. * @param date 时间
  173. * @param weeks 减少的周数
  174. * @return 设置后的时间
  175. */
  176. public static Date minusWeeks(Date date, int weeks) {
  177. return DateUtil.minus(date, Period.ofWeeks(weeks));
  178. }
  179.  
  180. /**
  181. * 减少天
  182. *
  183. * @param date 时间
  184. * @param days 减少的天数
  185. * @return 设置后的时间
  186. */
  187. public static Date minusDays(Date date, long days) {
  188. return DateUtil.minus(date, Duration.ofDays(days));
  189. }
  190.  
  191. /**
  192. * 减少小时
  193. *
  194. * @param date 时间
  195. * @param hours 减少的小时数
  196. * @return 设置后的时间
  197. */
  198. public static Date minusHours(Date date, long hours) {
  199. return DateUtil.minus(date, Duration.ofHours(hours));
  200. }
  201.  
  202. /**
  203. * 减少分钟
  204. *
  205. * @param date 时间
  206. * @param minutes 减少的分钟数
  207. * @return 设置后的时间
  208. */
  209. public static Date minusMinutes(Date date, long minutes) {
  210. return DateUtil.minus(date, Duration.ofMinutes(minutes));
  211. }
  212.  
  213. /**
  214. * 减少秒
  215. *
  216. * @param date 时间
  217. * @param seconds 减少的秒数
  218. * @return 设置后的时间
  219. */
  220. public static Date minusSeconds(Date date, long seconds) {
  221. return DateUtil.minus(date, Duration.ofSeconds(seconds));
  222. }
  223.  
  224. /**
  225. * 减少毫秒
  226. *
  227. * @param date 时间
  228. * @param millis 减少的毫秒数
  229. * @return 设置后的时间
  230. */
  231. public static Date minusMillis(Date date, long millis) {
  232. return DateUtil.minus(date, Duration.ofMillis(millis));
  233. }
  234.  
  235. /**
  236. * 减少纳秒
  237. *
  238. * @param date 时间
  239. * @param nanos 减少的纳秒数
  240. * @return 设置后的时间
  241. */
  242. public static Date minusNanos(Date date, long nanos) {
  243. return DateUtil.minus(date, Duration.ofNanos(nanos));
  244. }
  245.  
  246. /**
  247. * 日期减少时间量
  248. *
  249. * @param date 时间
  250. * @param amount 时间量
  251. * @return 设置后的时间
  252. */
  253. public static Date minus(Date date, TemporalAmount amount) {
  254. Instant instant = date.toInstant();
  255. return Date.from(instant.minus(amount));
  256. }
  257.  
  258. /**
  259. * 设置日期属性
  260. *
  261. * @param date 时间
  262. * @param calendarField 更改的属性
  263. * @param amount 更改数,-1表示减少
  264. * @return 设置后的时间
  265. */
  266. private static Date set(Date date, int calendarField, int amount) {
  267. Assert.notNull(date, "The date must not be null");
  268. Calendar c = Calendar.getInstance();
  269. c.setLenient(false);
  270. c.setTime(date);
  271. c.add(calendarField, amount);
  272. return c.getTime();
  273. }
  274.  
  275. /**
  276. * 日期时间格式化
  277. *
  278. * @param date 时间
  279. * @return 格式化后的时间
  280. */
  281. public static String formatDateTime(Date date) {
  282. return DATETIME_FORMAT.format(date);
  283. }
  284.  
  285. /**
  286. * 日期时间格式化
  287. *
  288. * @param date 时间
  289. * @return 格式化后的时间
  290. */
  291. public static String formatDateTimeMini(Date date) {
  292. return DATETIME_MINI_FORMAT.format(date);
  293. }
  294.  
  295. /**
  296. * 日期格式化
  297. *
  298. * @param date 时间
  299. * @return 格式化后的时间
  300. */
  301. public static String formatDate(Date date) {
  302. return DATE_FORMAT.format(date);
  303. }
  304.  
  305. /**
  306. * 时间格式化
  307. *
  308. * @param date 时间
  309. * @return 格式化后的时间
  310. */
  311. public static String formatTime(Date date) {
  312. return TIME_FORMAT.format(date);
  313. }
  314.  
  315. /**
  316. * 日期格式化
  317. *
  318. * @param date 时间
  319. * @param pattern 表达式
  320. * @return 格式化后的时间
  321. */
  322. public static String format(Date date, String pattern) {
  323. return ConcurrentDateFormat.of(pattern).format(date);
  324. }
  325.  
  326. /**
  327. * java8 日期时间格式化
  328. *
  329. * @param temporal 时间
  330. * @return 格式化后的时间
  331. */
  332. public static String formatDateTime(TemporalAccessor temporal) {
  333. return DATETIME_FORMATTER.format(temporal);
  334. }
  335.  
  336. /**
  337. * java8 日期时间格式化
  338. *
  339. * @param temporal 时间
  340. * @return 格式化后的时间
  341. */
  342. public static String formatDateTimeMini(TemporalAccessor temporal) {
  343. return DATETIME_MINI_FORMATTER.format(temporal);
  344. }
  345.  
  346. /**
  347. * java8 日期时间格式化
  348. *
  349. * @param temporal 时间
  350. * @return 格式化后的时间
  351. */
  352. public static String formatDate(TemporalAccessor temporal) {
  353. return DATE_FORMATTER.format(temporal);
  354. }
  355.  
  356. /**
  357. * java8 时间格式化
  358. *
  359. * @param temporal 时间
  360. * @return 格式化后的时间
  361. */
  362. public static String formatTime(TemporalAccessor temporal) {
  363. return TIME_FORMATTER.format(temporal);
  364. }
  365.  
  366. /**
  367. * java8 日期格式化
  368. *
  369. * @param temporal 时间
  370. * @param pattern 表达式
  371. * @return 格式化后的时间
  372. */
  373. public static String format(TemporalAccessor temporal, String pattern) {
  374. return DateTimeFormatter.ofPattern(pattern).format(temporal);
  375. }
  376.  
  377. /**
  378. * 将字符串转换为时间
  379. *
  380. * @param dateStr 时间字符串
  381. * @param pattern 表达式
  382. * @return 时间
  383. */
  384. public static Date parse(String dateStr, String pattern) {
  385. ConcurrentDateFormat format = ConcurrentDateFormat.of(pattern);
  386. try {
  387. return format.parse(dateStr);
  388. } catch (ParseException e) {
  389. throw Exceptions.unchecked(e);
  390. }
  391. }
  392.  
  393. /**
  394. * 将字符串转换为时间
  395. *
  396. * @param dateStr 时间字符串
  397. * @param format ConcurrentDateFormat
  398. * @return 时间
  399. */
  400. public static Date parse(String dateStr, ConcurrentDateFormat format) {
  401. try {
  402. return format.parse(dateStr);
  403. } catch (ParseException e) {
  404. throw Exceptions.unchecked(e);
  405. }
  406. }
  407.  
  408. /**
  409. * 将字符串转换为时间
  410. *
  411. * @param dateStr 时间字符串
  412. * @param pattern 表达式
  413. * @return 时间
  414. */
  415. public static <T> T parse(String dateStr, String pattern, TemporalQuery<T> query) {
  416. return DateTimeFormatter.ofPattern(pattern).parse(dateStr, query);
  417. }
  418.  
  419. /**
  420. * 时间转 Instant
  421. *
  422. * @param dateTime 时间
  423. * @return Instant
  424. */
  425. public static Instant toInstant(LocalDateTime dateTime) {
  426. return dateTime.atZone(ZoneId.systemDefault()).toInstant();
  427. }
  428.  
  429. /**
  430. * Instant 转 时间
  431. *
  432. * @param instant Instant
  433. * @return Instant
  434. */
  435. public static LocalDateTime toDateTime(Instant instant) {
  436. return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
  437. }
  438.  
  439. /**
  440. * 转换成 date
  441. *
  442. * @param dateTime LocalDateTime
  443. * @return Date
  444. */
  445. public static Date toDate(LocalDateTime dateTime) {
  446. return Date.from(DateUtil.toInstant(dateTime));
  447. }
  448.  
  449. /**
  450. * 转换成 date
  451. *
  452. * @param localDate LocalDate
  453. * @return Date
  454. */
  455. public static Date toDate(final LocalDate localDate) {
  456. return Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
  457. }
  458.  
  459. /**
  460. * Converts local date time to Calendar.
  461. */
  462. public static Calendar toCalendar(final LocalDateTime localDateTime) {
  463. return GregorianCalendar.from(ZonedDateTime.of(localDateTime, ZoneId.systemDefault()));
  464. }
  465.  
  466. /**
  467. * localDateTime 转换成毫秒数
  468. *
  469. * @param localDateTime LocalDateTime
  470. * @return long
  471. */
  472. public static long toMilliseconds(final LocalDateTime localDateTime) {
  473. return localDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
  474. }
  475.  
  476. /**
  477. * localDate 转换成毫秒数
  478. *
  479. * @param localDate LocalDate
  480. * @return long
  481. */
  482. public static long toMilliseconds(LocalDate localDate) {
  483. return toMilliseconds(localDate.atStartOfDay());
  484. }
  485.  
  486. /**
  487. * 转换成java8 时间
  488. *
  489. * @param calendar 日历
  490. * @return LocalDateTime
  491. */
  492. public static LocalDateTime fromCalendar(final Calendar calendar) {
  493. TimeZone tz = calendar.getTimeZone();
  494. ZoneId zid = tz == null ? ZoneId.systemDefault() : tz.toZoneId();
  495. return LocalDateTime.ofInstant(calendar.toInstant(), zid);
  496. }
  497.  
  498. /**
  499. * 转换成java8 时间
  500. *
  501. * @param instant Instant
  502. * @return LocalDateTime
  503. */
  504. public static LocalDateTime fromInstant(final Instant instant) {
  505. return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
  506. }
  507.  
  508. /**
  509. * 转换成java8 时间
  510. *
  511. * @param date Date
  512. * @return LocalDateTime
  513. */
  514. public static LocalDateTime fromDate(final Date date) {
  515. return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
  516. }
  517.  
  518. /**
  519. * 转换成java8 时间
  520. *
  521. * @param milliseconds 毫秒数
  522. * @return LocalDateTime
  523. */
  524. public static LocalDateTime fromMilliseconds(final long milliseconds) {
  525. return LocalDateTime.ofInstant(Instant.ofEpochMilli(milliseconds), ZoneId.systemDefault());
  526. }
  527.  
  528. /**
  529. * 比较2个时间差,跨度比较小
  530. *
  531. * @param startInclusive 开始时间
  532. * @param endExclusive 结束时间
  533. * @return 时间间隔
  534. */
  535. public static Duration between(Temporal startInclusive, Temporal endExclusive) {
  536. return Duration.between(startInclusive, endExclusive);
  537. }
  538.  
  539. /**
  540. * 比较2个时间差,跨度比较大,年月日为单位
  541. *
  542. * @param startDate 开始时间
  543. * @param endDate 结束时间
  544. * @return 时间间隔
  545. */
  546. public static Period between(LocalDate startDate, LocalDate endDate) {
  547. return Period.between(startDate, endDate);
  548. }
  549.  
  550. /**
  551. * 比较2个 时间差
  552. *
  553. * @param startDate 开始时间
  554. * @param endDate 结束时间
  555. * @return 时间间隔
  556. */
  557. public static Duration between(Date startDate, Date endDate) {
  558. return Duration.between(startDate.toInstant(), endDate.toInstant());
  559. }
  560.  
  561. /**
  562. * 获取今天的日期
  563. *
  564. * @return 时间
  565. */
  566. public static String today() {
  567. return format(new Date(), "yyyyMMdd");
  568. }
  569.  
  570. /**
  571. * 获取今天的时间
  572. *
  573. * @return 时间
  574. */
  575. public static String time() {
  576. return format(new Date(), PATTERN_DATETIME_MINI);
  577. }
  578.  
  579. /**
  580. * 获取指定年月的第一天
  581. * @param year
  582. * @param month
  583. * @return
  584. */
  585. public static String getFirstDayOfMonth(int year, int month) {
  586. Calendar cal = Calendar.getInstance();
  587. //设置年份
  588. cal.set(Calendar.YEAR, year);
  589. //设置月份
  590. cal.set(Calendar.MONTH, month-1);
  591. //获取某月最小天数
  592. int firstDay = cal.getMinimum(Calendar.DATE);
  593. //设置日历中月份的最小天数
  594. cal.set(Calendar.DAY_OF_MONTH,firstDay);
  595. //格式化日期
  596. return DATE_FORMAT.format(cal.getTime());
  597. }
  598.  
  599. /**
  600. * 获取指定年月的最后一天
  601. * @param year
  602. * @param month
  603. * @return
  604. */
  605. public static String getLastDayOfMonth(int year, int month) {
  606. Calendar cal = Calendar.getInstance();
  607. //设置年份
  608. cal.set(Calendar.YEAR, year);
  609. //设置月份
  610. cal.set(Calendar.MONTH, month-1);
  611. //获取某月最大天数
  612. int lastDay = cal.getActualMaximum(Calendar.DATE);
  613. //设置日历中月份的最大天数
  614. cal.set(Calendar.DAY_OF_MONTH, lastDay);
  615. //格式化日期
  616. return DATE_FORMAT.format(cal.getTime());
  617. }
  618.  
  619. /**
  620. * 获取指定年月的下个月第一天
  621. * @param year
  622. * @param month
  623. * @return
  624. */
  625. public static String getFirstDayOfNextMonth(int year, int month) {
  626. Calendar cal = Calendar.getInstance();
  627. //设置年份
  628. cal.set(Calendar.YEAR, year);
  629. //设置月份
  630. cal.set(Calendar.MONTH, month);
  631. //获取某月最小天数
  632. int firstDay = cal.getMinimum(Calendar.DATE);
  633. //设置日历中月份的最小天数
  634. cal.set(Calendar.DAY_OF_MONTH,firstDay);
  635. //格式化日期
  636. return DATE_FORMAT.format(cal.getTime());
  637. }
  638. }

BigDecimal运算工具类

  1. import java.math.BigDecimal;
  2.  
  3. /**
  4. * 用于高精确处理常用的数学运算
  5. */
  6. public class ArithmeticUtils {
  7. //默认除法运算精度
  8. private static final int DEF_DIV_SCALE = 10;
  9.  
  10. /**
  11. * 提供精确的加法运算
  12. *
  13. * @param v1 被加数
  14. * @param v2 加数
  15. * @return 两个参数的和
  16. */
  17.  
  18. public static double add(double v1, double v2) {
  19. BigDecimal b1 = new BigDecimal(Double.toString(v1));
  20. BigDecimal b2 = new BigDecimal(Double.toString(v2));
  21. return b1.add(b2).doubleValue();
  22. }
  23.  
  24. /**
  25. * 提供精确的加法运算
  26. *
  27. * @param v1 被加数
  28. * @param v2 加数
  29. * @return 两个参数的和
  30. */
  31. public static BigDecimal add(String v1, String v2) {
  32. BigDecimal b1 = new BigDecimal(v1);
  33. BigDecimal b2 = new BigDecimal(v2);
  34. return b1.add(b2);
  35. }
  36.  
  37. /**
  38. * 提供精确的加法运算
  39. *
  40. * @param v1 被加数
  41. * @param v2 加数
  42. * @param scale 保留scale 位小数
  43. * @return 两个参数的和
  44. */
  45. public static String add(String v1, String v2, int scale) {
  46. if (scale < 0) {
  47. throw new IllegalArgumentException(
  48. "The scale must be a positive integer or zero");
  49. }
  50. BigDecimal b1 = new BigDecimal(v1);
  51. BigDecimal b2 = new BigDecimal(v2);
  52. return b1.add(b2).setScale(scale, BigDecimal.ROUND_HALF_UP).toString();
  53. }
  54.  
  55. /**
  56. * 提供精确的减法运算
  57. *
  58. * @param v1 被减数
  59. * @param v2 减数
  60. * @return 两个参数的差
  61. */
  62. public static double sub(double v1, double v2) {
  63. BigDecimal b1 = new BigDecimal(Double.toString(v1));
  64. BigDecimal b2 = new BigDecimal(Double.toString(v2));
  65. return b1.subtract(b2).doubleValue();
  66. }
  67.  
  68. /**
  69. * 提供精确的减法运算。
  70. *
  71. * @param v1 被减数
  72. * @param v2 减数
  73. * @return 两个参数的差
  74. */
  75. public static BigDecimal sub(String v1, String v2) {
  76. BigDecimal b1 = new BigDecimal(v1);
  77. BigDecimal b2 = new BigDecimal(v2);
  78. return b1.subtract(b2);
  79. }
  80.  
  81. /**
  82. * 提供精确的减法运算
  83. *
  84. * @param v1 被减数
  85. * @param v2 减数
  86. * @param scale 保留scale 位小数
  87. * @return 两个参数的差
  88. */
  89. public static String sub(String v1, String v2, int scale) {
  90. if (scale < 0) {
  91. throw new IllegalArgumentException(
  92. "The scale must be a positive integer or zero");
  93. }
  94. BigDecimal b1 = new BigDecimal(v1);
  95. BigDecimal b2 = new BigDecimal(v2);
  96. return b1.subtract(b2).setScale(scale, BigDecimal.ROUND_HALF_UP).toString();
  97. }
  98.  
  99. /**
  100. * 提供精确的乘法运算
  101. *
  102. * @param v1 被乘数
  103. * @param v2 乘数
  104. * @return 两个参数的积
  105. */
  106. public static double mul(double v1, double v2) {
  107. BigDecimal b1 = new BigDecimal(Double.toString(v1));
  108. BigDecimal b2 = new BigDecimal(Double.toString(v2));
  109. return b1.multiply(b2).doubleValue();
  110. }
  111.  
  112. /**
  113. * 提供精确的乘法运算
  114. *
  115. * @param v1 被乘数
  116. * @param v2 乘数
  117. * @return 两个参数的积
  118. */
  119. public static BigDecimal mul(String v1, String v2) {
  120. BigDecimal b1 = new BigDecimal(v1);
  121. BigDecimal b2 = new BigDecimal(v2);
  122. return b1.multiply(b2);
  123. }
  124.  
  125. /**
  126. * 提供精确的乘法运算
  127. *
  128. * @param v1 被乘数
  129. * @param v2 乘数
  130. * @param scale 保留scale 位小数
  131. * @return 两个参数的积
  132. */
  133. public static double mul(double v1, double v2, int scale) {
  134. BigDecimal b1 = new BigDecimal(Double.toString(v1));
  135. BigDecimal b2 = new BigDecimal(Double.toString(v2));
  136. return round(b1.multiply(b2).doubleValue(), scale);
  137. }
  138.  
  139. /**
  140. * 提供精确的乘法运算
  141. *
  142. * @param v1 被乘数
  143. * @param v2 乘数
  144. * @param scale 保留scale 位小数
  145. * @return 两个参数的积
  146. */
  147. public static String mul(String v1, String v2, int scale) {
  148. if (scale < 0) {
  149. throw new IllegalArgumentException(
  150. "The scale must be a positive integer or zero");
  151. }
  152. BigDecimal b1 = new BigDecimal(v1);
  153. BigDecimal b2 = new BigDecimal(v2);
  154. return b1.multiply(b2).setScale(scale, BigDecimal.ROUND_HALF_UP).toString();
  155. }
  156.  
  157. /**
  158. * 提供(相对)精确的除法运算,当发生除不尽的情况时,精确到
  159. * 小数点以后10位,以后的数字四舍五入
  160. *
  161. * @param v1 被除数
  162. * @param v2 除数
  163. * @return 两个参数的商
  164. */
  165.  
  166. public static double div(double v1, double v2) {
  167. return div(v1, v2, DEF_DIV_SCALE);
  168. }
  169.  
  170. /**
  171. * 提供(相对)精确的除法运算。当发生除不尽的情况时,由scale参数指
  172. * 定精度,以后的数字四舍五入
  173. *
  174. * @param v1 被除数
  175. * @param v2 除数
  176. * @param scale 表示表示需要精确到小数点以后几位。
  177. * @return 两个参数的商
  178. */
  179. public static double div(double v1, double v2, int scale) {
  180. if (scale < 0) {
  181. throw new IllegalArgumentException("The scale must be a positive integer or zero");
  182. }
  183. BigDecimal b1 = new BigDecimal(Double.toString(v1));
  184. BigDecimal b2 = new BigDecimal(Double.toString(v2));
  185. return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
  186. }
  187.  
  188. /**
  189. * 提供(相对)精确的除法运算。当发生除不尽的情况时,由scale参数指
  190. * 定精度,以后的数字四舍五入
  191. *
  192. * @param v1 被除数
  193. * @param v2 除数
  194. * @param scale 表示需要精确到小数点以后几位
  195. * @return 两个参数的商
  196. */
  197. public static String div(String v1, String v2, int scale) {
  198. if (scale < 0) {
  199. throw new IllegalArgumentException("The scale must be a positive integer or zero");
  200. }
  201. BigDecimal b1 = new BigDecimal(v1);
  202. BigDecimal b2 = new BigDecimal(v1);
  203. return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).toString();
  204. }
  205.  
  206. /**
  207. * 提供精确的小数位四舍五入处理
  208. *
  209. * @param v 需要四舍五入的数字
  210. * @param scale 小数点后保留几位
  211. * @return 四舍五入后的结果
  212. */
  213. public static double round(double v, int scale) {
  214. if (scale < 0) {
  215. throw new IllegalArgumentException("The scale must be a positive integer or zero");
  216. }
  217. BigDecimal b = new BigDecimal(Double.toString(v));
  218. return b.setScale(scale, BigDecimal.ROUND_HALF_UP).doubleValue();
  219. }
  220.  
  221. /**
  222. * 提供精确的小数位四舍五入处理
  223. *
  224. * @param v 需要四舍五入的数字
  225. * @param scale 小数点后保留几位
  226. * @return 四舍五入后的结果
  227. */
  228. public static String round(String v, int scale) {
  229. if (scale < 0) {
  230. throw new IllegalArgumentException(
  231. "The scale must be a positive integer or zero");
  232. }
  233. BigDecimal b = new BigDecimal(v);
  234. return b.setScale(scale, BigDecimal.ROUND_HALF_UP).toString();
  235. }
  236.  
  237. /**
  238. * 取余数
  239. *
  240. * @param v1 被除数
  241. * @param v2 除数
  242. * @param scale 小数点后保留几位
  243. * @return 余数
  244. */
  245. public static String remainder(String v1, String v2, int scale) {
  246. if (scale < 0) {
  247. throw new IllegalArgumentException(
  248. "The scale must be a positive integer or zero");
  249. }
  250. BigDecimal b1 = new BigDecimal(v1);
  251. BigDecimal b2 = new BigDecimal(v2);
  252. return b1.remainder(b2).setScale(scale, BigDecimal.ROUND_HALF_UP).toString();
  253. }
  254.  
  255. /**
  256. * 取余数 BigDecimal
  257. *
  258. * @param v1 被除数
  259. * @param v2 除数
  260. * @param scale 小数点后保留几位
  261. * @return 余数
  262. */
  263. public static BigDecimal remainder(BigDecimal v1, BigDecimal v2, int scale) {
  264. if (scale < 0) {
  265. throw new IllegalArgumentException(
  266. "The scale must be a positive integer or zero");
  267. }
  268. return v1.remainder(v2).setScale(scale, BigDecimal.ROUND_HALF_UP);
  269. }
  270.  
  271. /**
  272. * 比较大小
  273. *
  274. * @param v1 被比较数
  275. * @param v2 比较数
  276. * @return 如果v1 大于v2 则 返回true 否则false
  277. */
  278. public static boolean compare(String v1, String v2) {
  279. BigDecimal b1 = new BigDecimal(v1);
  280. BigDecimal b2 = new BigDecimal(v2);
  281. int bj = b1.compareTo(b2);
  282. boolean res;
  283. if (bj > 0)
  284. res = true;
  285. else
  286. res = false;
  287. return res;
  288. }
  289. }

  1. /**
  2. * @Description: Double类型运算工具类
  3. */
  4. public class DoubleUtil {
  5.  
  6. /**
  7. * 提供精确的加法运算。
  8. *
  9. * @param v1
  10. * 被加数
  11. * @param v2
  12. * 加数
  13. * @return 两个参数的和
  14. */
  15.  
  16. public static double add(double v1, double v2)
  17. {
  18. BigDecimal b1 = new BigDecimal(Double.toString(v1));
  19. BigDecimal b2 = new BigDecimal(Double.toString(v2));
  20. return b1.add(b2).doubleValue();
  21. }
  22.  
  23. /**
  24. * 提供精确的减法运算。
  25. *
  26. * @param v1
  27. * 被减数
  28. * @param v2
  29. * 减数
  30. * @return 两个参数的差
  31. */
  32.  
  33. public static double sub(double v1, double v2)
  34. {
  35. BigDecimal b1 = new BigDecimal(Double.toString(v1));
  36. BigDecimal b2 = new BigDecimal(Double.toString(v2));
  37. return b1.subtract(b2).doubleValue();
  38. }
  39.  
  40. /**
  41. * 相除
  42. */
  43.  
  44. /**
  45. * double 除法
  46. *
  47. * @param d1
  48. * @param d2
  49. * @param scale
  50. * 四舍五入 小数点位数
  51. * @return
  52. */
  53. public static double div(double d1, double d2, int scale) {
  54. // 当然在此之前,你要判断分母是否为0,
  55. // 为0你可以根据实际需求做相应的处理
  56.  
  57. BigDecimal bd1 = new BigDecimal(Double.toString(d1));
  58. BigDecimal bd2 = new BigDecimal(Double.toString(d2));
  59.  
  60. try
  61. {
  62. return bd1.divide(bd2, scale, BigDecimal.ROUND_DOWN).doubleValue();
  63. } catch (Exception e)
  64. {
  65. e.printStackTrace();
  66. return 0;
  67. }
  68.  
  69. }
  70.  
  71. /**
  72. * 提供精确的乘法运算。
  73. * @param v1 被乘数
  74. * @param v2 乘数
  75. * @return 两个参数的积
  76. */
  77.  
  78. public static double mul(double v1,double v2){
  79. BigDecimal b1 = new BigDecimal(Double.toString(v1));
  80. BigDecimal b2 = new BigDecimal(Double.toString(v2));
  81. return b1.multiply(b2).doubleValue();
  82. }
  83.  
  84. /**
  85. * 比较两个double值的大小
  86. * @param v1 值1
  87. * @param v2 值2
  88. * @return 比较结果 -1:v1<v2; 0:v1; 1:v1>v2;
  89. */
  90. public static Integer compare(double v1, double v2) {
  91. BigDecimal b1 = BigDecimal.valueOf(v1);
  92. BigDecimal b2 = BigDecimal.valueOf(v2);
  93.  
  94. return b1.compareTo(b2);
  95. }
  96. /**
  97. * 按规则加减
  98. *
  99. * @param v1
  100. * 被加数
  101. * @param v2
  102. * 加数
  103. * @param scale
  104. * 保留小数位
  105. * @param roundUp
  106. * 保留规则:
  107. * BigDecimal.ROUND_HALF_DOWN也是五舍六入,
  108. * BigDecimal.ROUND_UP表示进位处理(就是直接加1),
  109. * BigDecimal.ROUND_DOWN表示直接去掉尾数
  110. * @return 两个参数的和
  111. */
  112.  
  113. public static Double addFormant(double v1, double v2, int scale, int roundUp) {
  114. BigDecimal b1 = new BigDecimal(Double.toString(v1));
  115. BigDecimal b2 = new BigDecimal(Double.toString(v2));
  116. return b1.add(b2).setScale(scale, roundUp).doubleValue();
  117. }
  118. }

  1. import java.math.BigDecimal;
  2.  
  3. /**
  4. */
  5. public class MathUtil {
  6. /**
  7. * 乘法
  8. * @param objects
  9. * @return
  10. */
  11. public static BigDecimal multiply(Object...objects ){
  12. BigDecimal sum = new BigDecimal("1");
  13. for (Object objectValue : objects) {
  14. if(objectValue ==null){
  15. objectValue = 0;
  16. }
  17. if(objectValue instanceof BigDecimal){
  18. sum = sum.multiply((BigDecimal) objectValue);
  19. }else{
  20. sum = sum.multiply(new BigDecimal(objectValue.toString()));
  21. }
  22. }
  23. return sum;
  24. }
  25.  
  26. /**
  27. * 加法
  28. * @param objects
  29. * @return
  30. */
  31. public static BigDecimal add(Object...objects ){
  32. BigDecimal sum = new BigDecimal("0");
  33. for (Object objectValue : objects) {
  34. if(objectValue ==null){
  35. objectValue = 0;
  36. }
  37. if(objectValue instanceof BigDecimal){
  38. sum = sum.add((BigDecimal) objectValue);
  39. }else{
  40. sum = sum.add(new BigDecimal(objectValue.toString()));
  41. }
  42. }
  43. return sum;
  44. }
  45.  
  46. /**
  47. * 减法
  48. * @param objects
  49. * @return
  50. */
  51. public static BigDecimal subtract(Object...objects ){
  52. BigDecimal sum = null;
  53. for (int i = 0; i < objects.length; i++) {
  54. Object objectValue = objects[i];
  55. if(objectValue ==null){
  56. objectValue= 0;
  57. }
  58. if(i==0){
  59. if(objectValue instanceof BigDecimal){
  60. sum = (BigDecimal) objectValue;
  61. }else{
  62. sum = new BigDecimal(objectValue.toString());
  63. }
  64. }else{
  65. if(objectValue instanceof BigDecimal){
  66. sum = sum.subtract((BigDecimal) objectValue);
  67. }else{
  68. sum = sum.subtract(new BigDecimal(objectValue.toString()));
  69. }
  70. }
  71. }
  72. return sum;
  73. }
  74.  
  75. /**
  76. * 除法
  77. * @param objects
  78. * @return
  79. */
  80. public static BigDecimal divide(Object...objects ){
  81. BigDecimal sum = null;
  82. if(objects.length>1){
  83. for (int i = 0; i < objects.length; i++) {
  84. Object objectValue = objects[i];
  85. if(i==0){
  86. if(objectValue ==null){
  87. return null;
  88. }
  89. if(objectValue instanceof BigDecimal){
  90. sum = (BigDecimal) objectValue;
  91. }else{
  92. sum = new BigDecimal(objectValue.toString());
  93. }
  94. }else{
  95. if(objectValue ==null){
  96. return null;
  97. }
  98. if(objectValue instanceof BigDecimal){
  99. sum = sum.divide((BigDecimal) objectValue);
  100. }else{
  101. sum = sum.divide(new BigDecimal(objectValue.toString()));
  102. }
  103. }
  104. }
  105. return sum;
  106. }else{
  107. return null;
  108. }
  109. }
  110. }

异常处理工具类

  1. /**
  2. * 异常处理工具类
  3. *
  4. */
  5. @UtilityClass
  6. public class Exceptions {
  7.  
  8. /**
  9. * 将CheckedException转换为UncheckedException.
  10. *
  11. * @param e Throwable
  12. * @return {RuntimeException}
  13. */
  14. public static RuntimeException unchecked(Throwable e) {
  15. if (e instanceof Error) {
  16. throw (Error) e;
  17. } else if (e instanceof IllegalAccessException ||
  18. e instanceof IllegalArgumentException ||
  19. e instanceof NoSuchMethodException) {
  20. return new IllegalArgumentException(e);
  21. } else if (e instanceof InvocationTargetException) {
  22. return new RuntimeException(((InvocationTargetException) e).getTargetException());
  23. } else if (e instanceof RuntimeException) {
  24. return (RuntimeException) e;
  25. } else if (e instanceof InterruptedException) {
  26. Thread.currentThread().interrupt();
  27. }
  28. return Exceptions.runtime(e);
  29. }
  30.  
  31. /**
  32. * 不采用 RuntimeException 包装,直接抛出,使异常更加精准
  33. *
  34. * @param throwable Throwable
  35. * @param <T> 泛型标记
  36. * @return Throwable
  37. * @throws T 泛型
  38. */
  39. @SuppressWarnings("unchecked")
  40. private static <T extends Throwable> T runtime(Throwable throwable) throws T {
  41. throw (T) throwable;
  42. }
  43.  
  44. /**
  45. * 代理异常解包
  46. *
  47. * @param wrapped 包装过得异常
  48. * @return 解包后的异常
  49. */
  50. public static Throwable unwrap(Throwable wrapped) {
  51. Throwable unwrapped = wrapped;
  52. while (true) {
  53. if (unwrapped instanceof InvocationTargetException) {
  54. unwrapped = ((InvocationTargetException) unwrapped).getTargetException();
  55. } else if (unwrapped instanceof UndeclaredThrowableException) {
  56. unwrapped = ((UndeclaredThrowableException) unwrapped).getUndeclaredThrowable();
  57. } else {
  58. return unwrapped;
  59. }
  60. }
  61. }
  62. }

Http请求工具类

  1. import com.alibaba.fastjson.JSON;
  2. import com.alibaba.fastjson.JSONObject;
  3. import lombok.extern.slf4j.Slf4j;
  4. import org.springframework.http.*;
  5. import org.springframework.util.LinkedMultiValueMap;
  6. import org.springframework.util.MultiValueMap;
  7. import org.springframework.web.client.RestClientException;
  8. import org.springframework.web.client.RestTemplate;
  9.  
  10. import java.util.Map;
  11.  
  12. /**
  13. * Http请求工具类
  14. *
  15. * @author yl
  16. */
  17. @Slf4j
  18. public class HttpUtil {
  19.  
  20. private static final String AUTHORIZATION = "Authorization";
  21.  
  22. /**
  23. * GET请求
  24. *
  25. * @param url 请求url
  26. * @param token 请求token
  27. * @return
  28. */
  29. public static String get(String url, String token) {
  30.  
  31. HttpHeaders httpHeaders = new HttpHeaders();
  32. httpHeaders.add(AUTHORIZATION, token);
  33.  
  34. MultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>();
  35. HttpEntity<MultiValueMap> requestEntity = new HttpEntity<MultiValueMap>(requestBody, httpHeaders);
  36. RestTemplate restTemplate = new RestTemplate();
  37. if (log.isInfoEnabled()) {
  38. log.info("[http-get] requestUrl: {}", url);
  39. }
  40. ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
  41. String result = response.getBody();
  42. if (log.isInfoEnabled()) {
  43. log.info("[http-get] response: {}", result);
  44. }
  45. return result;
  46. }
  47.  
  48. /**
  49. * application/json方式提交数据 自定义请求头
  50. *
  51. * @param url
  52. * @param object
  53. * @param headerMap
  54. * @return
  55. */
  56. public static String postWithHeader(String url, Object object, Map<String, String> headerMap) {
  57. String body = "";
  58. try {
  59. HttpHeaders httpHeaders = new HttpHeaders();
  60. httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
  61. httpHeaders.add(HttpHeaders.AUTHORIZATION, headerMap.get(HttpHeaders.AUTHORIZATION));
  62. log.info("地址 : " + url + "\n" + "参数 : " + JSON.toJSONString(object) + "\n" + "请求头 : " + httpHeaders.toString());
  63. //设置参数
  64. HttpEntity<Object> requestEntity = new HttpEntity<>(object, httpHeaders);
  65. RestTemplate restTemplate = new RestTemplate();
  66. ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, requestEntity, String.class);
  67. body = responseEntity.getBody();
  68. } catch (RestClientException e) {
  69. e.printStackTrace();
  70. log.error("Rest调用异常!!!地址 : " + url + "\n" + "参数 : " + JSON.toJSONString(object) + "\n" + "请求头 : " + headerMap.toString(), e);
  71. }
  72. return body;
  73. }
  74.  
  75. /**
  76. * post请求带请求体
  77. * @param url
  78. * @param requestBody
  79. * @return
  80. */
  81. public static JSONObject postJson(String url, Object requestBody) {
  82. RestTemplate restTemplate = new RestTemplate();
  83. log.info("[http] requestUrl: " + url);
  84. if (requestBody != null) {
  85. log.info("[http] requestBody:" + JSON.toJSONString(requestBody));
  86. }
  87. JSONObject response = restTemplate.postForObject(url, requestBody, JSONObject.class);
  88. log.info("[http] response:" + response.toJSONString());
  89. return response;
  90. }
  91. }

Jackson工具类

  1. import com.fasterxml.jackson.core.JsonGenerationException;
  2. import com.fasterxml.jackson.core.JsonParseException;
  3. import com.fasterxml.jackson.databind.JsonMappingException;
  4. import com.fasterxml.jackson.databind.ObjectMapper;
  5. import lombok.extern.slf4j.Slf4j;
  6.  
  7. import java.io.IOException;
  8.  
  9. @Slf4j
  10. public class JacksonUtil {
  11.  
  12. private final static ObjectMapper OBJECT_MAPPER = new ObjectMapper();
  13.  
  14. /**
  15. * 获取实体
  16. * @return ObjectMapper
  17. */
  18. private static ObjectMapper getInstance() {
  19. return OBJECT_MAPPER;
  20. }
  21.  
  22. /**
  23. * bean、array、List、Map --> json
  24. *
  25. * @param obj obj
  26. * @return json
  27. */
  28. public static String writeValueAsString(Object obj) {
  29. try {
  30. return getInstance().writeValueAsString(obj);
  31. } catch (JsonGenerationException e) {
  32. log.error(e.getMessage(), e);
  33. } catch (JsonMappingException e) {
  34. log.error(e.getMessage(), e);
  35. } catch (IOException e) {
  36. log.error(e.getMessage(), e);
  37. }
  38. return null;
  39. }
  40.  
  41. /**
  42. * string --> bean、Map、List(array)
  43. *
  44. * @param jsonStr jsonStr
  45. * @param clazz 类型
  46. * @return obj 对象
  47. */
  48. public static <T> T readValue(String jsonStr, Class<T> clazz) {
  49. try {
  50. return getInstance().readValue(jsonStr, clazz);
  51. } catch (JsonParseException e) {
  52. log.error(e.getMessage(), e);
  53. } catch (JsonMappingException e) {
  54. log.error(e.getMessage(), e);
  55. } catch (IOException e) {
  56. log.error(e.getMessage(), e);
  57. }
  58. return null;
  59. }
  60. }

日志格式生成类

  1. import com.alibaba.druid.util.StringUtils;
  2. import com.oristand.common.model.LogType;
  3.  
  4. /**
  5. * 生成[标题][大类][小类][过滤1]..格式log
  6. */
  7. public class LogCreate {
  8.  
  9. /**
  10. *
  11. * @param logTitle log标题
  12. * @param logType1 log大类型
  13. * @param logType2 log小类型
  14. * @param filters 过滤字段,用于查询日志
  15. * @return
  16. */
  17. public static String create(String logTitle, LogType logType1, LogType logType2, String... filters) {
  18. StringBuilder sb = new StringBuilder();
  19. sb.append("[").append(StringUtils.isEmpty(logTitle) ? "" : logTitle).append("]");
  20. sb.append("[").append(null == logType1 ? "" : logType1.getDesc()).append("]");
  21. sb.append("[").append(null == logType2 ? "" : logType2.getDesc()).append("]");
  22. for (String filter : filters) {
  23. sb.append("[").append(StringUtils.isEmpty(filter) ? "" : filter).append("]");
  24. }
  25. return sb.toString();
  26. }
  27.  
  28. }

Redis工具类

  1. import org.springframework.beans.factory.annotation.Autowired;
  2. import org.springframework.data.redis.core.RedisTemplate;
  3. import org.springframework.stereotype.Component;
  4. import org.springframework.util.CollectionUtils;
  5. import java.util.List;
  6. import java.util.Map;
  7. import java.util.Set;
  8. import java.util.concurrent.TimeUnit;
  9. /**
  10. * Redis工具类
  11. */
  12. @Component
  13. public final class RedisUtil {
  14. @Autowired
  15. private RedisTemplate<String, Object> redisTemplate;
  16. // =============================common============================
  17. /***
  18. * 读取所有以某字符开头的key
  19. * @param key key前缀
  20. * @return java.util.Set<java.lang.String>
  21. */
  22. public Set<String> vagueFindKey(String key) {
  23. return redisTemplate.keys(key + StringPool.ASTERISK);
  24. }
  25. /**
  26. * 以redis文件夹名称读取所有key
  27. *
  28. * @param key 文件夹key
  29. * @return java.util.Set<java.lang.String>
  30. */
  31. public Set<String> skey(String key) {
  32. return redisTemplate.keys(key + StringPool.COLON_STA);
  33. }
  34. /**
  35. * 指定缓存失效时间
  36. *
  37. * @param key 键
  38. * @param time 时间(秒)
  39. * @return
  40. */
  41. public Boolean expire(String key, long time) {
  42. try {
  43. if (time > 0) {
  44. redisTemplate.expire(key, time, TimeUnit.SECONDS);
  45. }
  46. return true;
  47. }
  48. catch (Exception e) {
  49. e.printStackTrace();
  50. return false;
  51. }
  52. }
  53. /**
  54. * 根据key 获取过期时间
  55. *
  56. * @param key 键 不能为null
  57. * @return 时间(秒) 返回0代表为永久有效
  58. */
  59. public long getExpire(String key) {
  60. return redisTemplate.getExpire(key, TimeUnit.SECONDS);
  61. }
  62. /**
  63. * 判断key是否存在
  64. *
  65. * @param key 键
  66. * @return true 存在 false不存在
  67. */
  68. public Boolean hasKey(String key) {
  69. try {
  70. return redisTemplate.hasKey(key);
  71. }
  72. catch (Exception e) {
  73. e.printStackTrace();
  74. return false;
  75. }
  76. }
  77. /**
  78. * 删除缓存
  79. *
  80. * @param key 可以传一个值 或多个
  81. */
  82. @SuppressWarnings("unchecked")
  83. public void del(String... key) {
  84. if (key != null && key.length > 0) {
  85. if (key.length == 1) {
  86. redisTemplate.delete(key[0]);
  87. } else {
  88. redisTemplate.delete(CollectionUtils.arrayToList(key));
  89. }
  90. }
  91. }
  92. // ============================String=============================
  93. /**
  94. * 普通缓存获取
  95. *
  96. * @param key 键
  97. * @return 值
  98. */
  99. public Object get(String key) {
  100. return key == null ? null : redisTemplate.opsForValue().get(key);
  101. }
  102. /**
  103. * 普通缓存放入
  104. *
  105. * @param key 键
  106. * @param value 值
  107. * @return true成功 false失败
  108. */
  109. public Boolean set(String key, Object value) {
  110. try {
  111. redisTemplate.opsForValue().set(key, value);
  112. return true;
  113. }
  114. catch (Exception e) {
  115. e.printStackTrace();
  116. return false;
  117. }
  118. }
  119. /**
  120. * 普通缓存放入并设置时间
  121. *
  122. * @param key 键
  123. * @param value 值
  124. * @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
  125. * @return true成功 false 失败
  126. */
  127. public Boolean set(String key, Object value, long time) {
  128. try {
  129. if (time > 0) {
  130. redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
  131. } else {
  132. set(key, value);
  133. }
  134. return true;
  135. }
  136. catch (Exception e) {
  137. e.printStackTrace();
  138. return false;
  139. }
  140. }
  141. /**
  142. * 递增
  143. *
  144. * @param key 键
  145. * @param delta 要增加几(大于0)
  146. * @return
  147. */
  148. public long incr(String key, long delta) {
  149. if (delta < 0) {
  150. throw new RuntimeException("递增因子必须大于0");
  151. }
  152. return redisTemplate.opsForValue().increment(key, delta);
  153. }
  154. /**
  155. * 递减
  156. *
  157. * @param key 键
  158. * @param delta 要减少几(小于0)
  159. * @return
  160. */
  161. public long decr(String key, long delta) {
  162. if (delta < 0) {
  163. throw new RuntimeException("递减因子必须大于0");
  164. }
  165. return redisTemplate.opsForValue().increment(key, -delta);
  166. }
  167. // ================================Map=================================
  168. /**
  169. * HashGet
  170. *
  171. * @param key 键 不能为null
  172. * @param item 项 不能为null
  173. * @return 值
  174. */
  175. public Object hget(String key, String item) {
  176. return redisTemplate.opsForHash().get(key, item);
  177. }
  178. /**
  179. * 获取hashKey对应的所有键值
  180. *
  181. * @param key 键
  182. * @return 对应的多个键值
  183. */
  184. public Map<Object, Object> hmget(String key) {
  185. return redisTemplate.opsForHash().entries(key);
  186. }
  187. /**
  188. * HashSet
  189. *
  190. * @param key 键
  191. * @param map 对应多个键值
  192. * @return true 成功 false 失败
  193. */
  194. public Boolean hmset(String key, Map<String, Object> map) {
  195. try {
  196. redisTemplate.opsForHash().putAll(key, map);
  197. return true;
  198. }
  199. catch (Exception e) {
  200. e.printStackTrace();
  201. return false;
  202. }
  203. }
  204. /**
  205. * HashSet 并设置时间
  206. *
  207. * @param key 键
  208. * @param map 对应多个键值
  209. * @param time 时间(秒)
  210. * @return true成功 false失败
  211. */
  212. public Boolean hmset(String key, Map<String, Object> map, long time) {
  213. try {
  214. redisTemplate.opsForHash().putAll(key, map);
  215. if (time > 0) {
  216. expire(key, time);
  217. }
  218. return true;
  219. }
  220. catch (Exception e) {
  221. e.printStackTrace();
  222. return false;
  223. }
  224. }
  225. /**
  226. * 向一张hash表中放入数据,如果不存在将创建
  227. *
  228. * @param key 键
  229. * @param item 项
  230. * @param value 值
  231. * @return true 成功 false失败
  232. */
  233. public Boolean hset(String key, String item, Object value) {
  234. try {
  235. redisTemplate.opsForHash().put(key, item, value);
  236. return true;
  237. }
  238. catch (Exception e) {
  239. e.printStackTrace();
  240. return false;
  241. }
  242. }
  243. /**
  244. * 向一张hash表中放入数据,如果不存在将创建
  245. *
  246. * @param key 键
  247. * @param item 项
  248. * @param value 值
  249. * @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
  250. * @return true 成功 false失败
  251. */
  252. public Boolean hset(String key, String item, Object value, long time) {
  253. try {
  254. redisTemplate.opsForHash().put(key, item, value);
  255. if (time > 0) {
  256. expire(key, time);
  257. }
  258. return true;
  259. }
  260. catch (Exception e) {
  261. e.printStackTrace();
  262. return false;
  263. }
  264. }
  265. /**
  266. * 删除hash表中的值
  267. *
  268. * @param key 键 不能为null
  269. * @param item 项 可以使多个 不能为null
  270. */
  271. public void hdel(String key, Object... item) {
  272. redisTemplate.opsForHash().delete(key, item);
  273. }
  274. /**
  275. * 判断hash表中是否有该项的值
  276. *
  277. * @param key 键 不能为null
  278. * @param item 项 不能为null
  279. * @return true 存在 false不存在
  280. */
  281. public Boolean hHasKey(String key, String item) {
  282. return redisTemplate.opsForHash().hasKey(key, item);
  283. }
  284. /**
  285. * hash递增 如果不存在,就会创建一个 并把新增后的值返回
  286. *
  287. * @param key 键
  288. * @param item 项
  289. * @param by 要增加几(大于0)
  290. * @return
  291. */
  292. public double hincr(String key, String item, double by) {
  293. return redisTemplate.opsForHash().increment(key, item, by);
  294. }
  295. /**
  296. * hash递减
  297. *
  298. * @param key 键
  299. * @param item 项
  300. * @param by 要减少记(小于0)
  301. * @return
  302. */
  303. public double hdecr(String key, String item, double by) {
  304. return redisTemplate.opsForHash().increment(key, item, -by);
  305. }
  306. // ============================set=============================
  307. /**
  308. * 根据key获取Set中的所有值
  309. *
  310. * @param key 键
  311. * @return
  312. */
  313. public Set<Object> sGet(String key) {
  314. try {
  315. return redisTemplate.opsForSet().members(key);
  316. }
  317. catch (Exception e) {
  318. e.printStackTrace();
  319. return null;
  320. }
  321. }
  322. /**
  323. * 根据value从一个set中查询,是否存在
  324. *
  325. * @param key 键
  326. * @param value 值
  327. * @return true 存在 false不存在
  328. */
  329. public Boolean sHasKey(String key, Object value) {
  330. try {
  331. return redisTemplate.opsForSet().isMember(key, value);
  332. }
  333. catch (Exception e) {
  334. e.printStackTrace();
  335. return false;
  336. }
  337. }
  338. /**
  339. * 将数据放入set缓存
  340. *
  341. * @param key 键
  342. * @param values 值 可以是多个
  343. * @return 成功个数
  344. */
  345. public long sSet(String key, Object... values) {
  346. try {
  347. return redisTemplate.opsForSet().add(key, values);
  348. }
  349. catch (Exception e) {
  350. e.printStackTrace();
  351. return 0;
  352. }
  353. }
  354. /**
  355. * 将set数据放入缓存
  356. *
  357. * @param key 键
  358. * @param time 时间(秒)
  359. * @param values 值 可以是多个
  360. * @return 成功个数
  361. */
  362. public long sSetAndTime(String key, long time, Object... values) {
  363. try {
  364. long count = redisTemplate.opsForSet().add(key, values);
  365. if (time > 0)
  366. expire(key, time);
  367. return count;
  368. }
  369. catch (Exception e) {
  370. e.printStackTrace();
  371. return 0;
  372. }
  373. }
  374. /**
  375. * 获取set缓存的长度
  376. *
  377. * @param key 键
  378. * @return
  379. */
  380. public long sGetSetSize(String key) {
  381. try {
  382. return redisTemplate.opsForSet().size(key);
  383. }
  384. catch (Exception e) {
  385. e.printStackTrace();
  386. return 0;
  387. }
  388. }
  389. /**
  390. * 移除值为value的
  391. *
  392. * @param key 键
  393. * @param values 值 可以是多个
  394. * @return 移除的个数
  395. */
  396. public long setRemove(String key, Object... values) {
  397. try {
  398. long count = redisTemplate.opsForSet().remove(key, values);
  399. return count;
  400. }
  401. catch (Exception e) {
  402. e.printStackTrace();
  403. return 0;
  404. }
  405. }
  406. // ===============================list=================================
  407. /**
  408. * 获取list缓存的内容
  409. *
  410. * @param key 键
  411. * @param start 开始
  412. * @param end 结束 0 到 -1代表所有值
  413. * @return
  414. */
  415. public List<Object> lGet(String key, long start, long end) {
  416. try {
  417. return redisTemplate.opsForList().range(key, start, end);
  418. }
  419. catch (Exception e) {
  420. e.printStackTrace();
  421. return null;
  422. }
  423. }
  424. /**
  425. * 获取list缓存的长度
  426. *
  427. * @param key 键
  428. * @return
  429. */
  430. public long lGetListSize(String key) {
  431. try {
  432. return redisTemplate.opsForList().size(key);
  433. }
  434. catch (Exception e) {
  435. e.printStackTrace();
  436. return 0;
  437. }
  438. }
  439. /**
  440. * 通过索引 获取list中的值
  441. *
  442. * @param key 键
  443. * @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
  444. * @return
  445. */
  446. public Object lGetIndex(String key, long index) {
  447. try {
  448. return redisTemplate.opsForList().index(key, index);
  449. }
  450. catch (Exception e) {
  451. e.printStackTrace();
  452. return null;
  453. }
  454. }
  455. /**
  456. * 将list放入缓存
  457. *
  458. * @param key 键
  459. * @param value 值
  460. * @return
  461. */
  462. public Boolean lSet(String key, Object value) {
  463. try {
  464. redisTemplate.opsForList().rightPush(key, value);
  465. return true;
  466. }
  467. catch (Exception e) {
  468. e.printStackTrace();
  469. return false;
  470. }
  471. }
  472. /**
  473. * 将list放入缓存
  474. *
  475. * @param key 键
  476. * @param value 值
  477. * @param time 时间(秒)
  478. * @return
  479. */
  480. public Boolean lSet(String key, Object value, long time) {
  481. try {
  482. redisTemplate.opsForList().rightPush(key, value);
  483. if (time > 0)
  484. expire(key, time);
  485. return true;
  486. }
  487. catch (Exception e) {
  488. e.printStackTrace();
  489. return false;
  490. }
  491. }
  492. /**
  493. * 将list放入缓存
  494. *
  495. * @param key 键
  496. * @param value 值
  497. * @return
  498. */
  499. public Boolean lSet(String key, List<Object> value) {
  500. try {
  501. redisTemplate.opsForList().rightPushAll(key, value);
  502. return true;
  503. }
  504. catch (Exception e) {
  505. e.printStackTrace();
  506. return false;
  507. }
  508. }
  509. /**
  510. * 将list放入缓存
  511. *
  512. * @param key 键
  513. * @param value 值
  514. * @param time 时间(秒)
  515. * @return
  516. */
  517. public Boolean lSet(String key, List<Object> value, long time) {
  518. try {
  519. redisTemplate.opsForList().rightPushAll(key, value);
  520. if (time > 0)
  521. expire(key, time);
  522. return true;
  523. }
  524. catch (Exception e) {
  525. e.printStackTrace();
  526. return false;
  527. }
  528. }
  529. /**
  530. * 根据索引修改list中的某条数据
  531. *
  532. * @param key 键
  533. * @param index 索引
  534. * @param value 值
  535. * @return
  536. */
  537. public Boolean lUpdateIndex(String key, long index, Object value) {
  538. try {
  539. redisTemplate.opsForList().set(key, index, value);
  540. return true;
  541. }
  542. catch (Exception e) {
  543. e.printStackTrace();
  544. return false;
  545. }
  546. }
  547. /**
  548. * 移除N个值为value
  549. *
  550. * @param key 键
  551. * @param count 移除多少个
  552. * @param value 值
  553. * @return 移除的个数
  554. */
  555. public long lRemove(String key, long count, Object value) {
  556. try {
  557. long remove = redisTemplate.opsForList().remove(key, count, value);
  558. return remove;
  559. }
  560. catch (Exception e) {
  561. e.printStackTrace();
  562. return 0;
  563. }
  564. }
  565. }

RestTemplateUtils

  1. import com.alibaba.fastjson.JSON;
  2. import lombok.extern.slf4j.Slf4j;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.http.HttpEntity;
  5. import org.springframework.http.HttpHeaders;
  6. import org.springframework.http.MediaType;
  7. import org.springframework.http.ResponseEntity;
  8. import org.springframework.stereotype.Component;
  9. import org.springframework.util.LinkedMultiValueMap;
  10. import org.springframework.web.client.RestClientException;
  11. import org.springframework.web.client.RestTemplate;
  12. import java.util.Map;
  13. @Component
  14. @Slf4j
  15. public class RestTemplateUtil
  16. {
  17. @Autowired
  18. private RestTemplate restTemplate;
  19. /**
  20. * application/json方式提交数据
  21. *
  22. * @param url
  23. * @param object
  24. * @return
  25. */
  26. public String post(String url, Object object)
  27. {
  28. String body = "";
  29. try
  30. {
  31. HttpHeaders httpHeaders = new HttpHeaders();
  32. httpHeaders.setContentType(MediaType.APPLICATION_JSON);
  33. //设置参数
  34. HttpEntity < Object > requestEntity = new HttpEntity < > (object, httpHeaders);
  35. log.info("地址 : " + url + "\n" + "参数 : " + JSON.toJSONString(object) + "\n" + "请求头 : " + httpHeaders.toString());
  36. ResponseEntity < String > responseEntity = restTemplate.postForEntity(url, requestEntity, String.class);
  37. body = responseEntity.getBody();
  38. }
  39. catch (RestClientException e)
  40. {
  41. e.printStackTrace();
  42. log.error("Rest调用异常!!!地址 : " + url + "\n" + "参数 : " + JSON.toJSONString(object), e);
  43. }
  44. return body;
  45. }
  46. /**
  47. * application/json方式提交数据 自定义请求头
  48. *
  49. * @param url
  50. * @param object
  51. * @param headerMap
  52. * @return
  53. */
  54. public String postWithHeader(String url, Object object, Map < String, String > headerMap)
  55. {
  56. String body = "";
  57. try
  58. {
  59. HttpHeaders httpHeaders = new HttpHeaders();
  60. httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
  61. if (headerMap != null && headerMap.size() != 0)
  62. {
  63. for (String s: headerMap.keySet())
  64. {
  65. httpHeaders.add(s, headerMap.get(s));
  66. }
  67. }
  68. log.info("地址 : " + url + "\n" + "参数 : " + JSON.toJSONString(object) + "\n" + "请求头 : " + httpHeaders.toString());
  69. //设置参数
  70. HttpEntity < Object > requestEntity = new HttpEntity < > (object, httpHeaders);
  71. ResponseEntity < String > responseEntity = restTemplate.postForEntity(url, requestEntity, String.class);
  72. body = responseEntity.getBody();
  73. }
  74. catch (RestClientException e)
  75. {
  76. e.printStackTrace();
  77. log.error("Rest调用异常!!!地址 : " + url + "\n" + "参数 : " + JSON.toJSONString(object) + "\n" + "请求头 : " + headerMap.toString(), e);
  78. }
  79. return body;
  80. }
  81. /**
  82. * 表单提交数据
  83. *
  84. * @param url
  85. * @param map
  86. * @return
  87. */
  88. public String postFrom(String url, Map < String, String > map)
  89. {
  90. String body = "";
  91. try
  92. {
  93. HttpHeaders httpHeaders = new HttpHeaders();
  94. httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
  95. LinkedMultiValueMap < String, String > multiValueMap = new LinkedMultiValueMap < > ();
  96. if (map != null && map.size() != 0)
  97. {
  98. for (Map.Entry < String, String > entry: map.entrySet())
  99. {
  100. multiValueMap.add(entry.getKey(), entry.getValue());
  101. }
  102. }
  103. //设置参数
  104. HttpEntity < LinkedMultiValueMap < String, String >> requestEntity = new HttpEntity < > (multiValueMap, httpHeaders);
  105. log.info("地址 : " + url + "\n" + "参数 : " + map.toString() + "\n" + "请求头 : " + httpHeaders.toString());
  106. ResponseEntity < String > responseEntity = restTemplate.postForEntity(url, requestEntity, String.class);
  107. body = responseEntity.getBody();
  108. }
  109. catch (RestClientException e)
  110. {
  111. e.printStackTrace();
  112. log.error("Rest调用异常!!!地址 : " + url + "\n" + "参数 : " + map.toString(), e);
  113. }
  114. return body;
  115. }
  116. /**
  117. * 表单提交数据 自定义请求头
  118. *
  119. * @param url
  120. * @param map
  121. * @param headerMap
  122. * @return
  123. */
  124. public String postFromWithHeader(String url, Map < String, String > map, Map < String, String > headerMap)
  125. {
  126. String body = "";
  127. try
  128. {
  129. HttpHeaders httpHeaders = new HttpHeaders();
  130. httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
  131. if (headerMap != null && headerMap.size() != 0)
  132. {
  133. for (String s: headerMap.keySet())
  134. {
  135. httpHeaders.add(s, headerMap.get(s));
  136. }
  137. }
  138. LinkedMultiValueMap < String, String > multiValueMap = new LinkedMultiValueMap < > ();
  139. if (map != null && map.size() != 0)
  140. {
  141. for (Map.Entry < String, String > entry: map.entrySet())
  142. {
  143. multiValueMap.add(entry.getKey(), entry.getValue());
  144. }
  145. }
  146. //设置参数
  147. HttpEntity < LinkedMultiValueMap < String, String >> requestEntity = new HttpEntity < > (multiValueMap, httpHeaders);
  148. log.info("地址 : " + url + "\n" + "参数 : " + map.toString() + "\n" + "请求头 : " + headerMap.toString());
  149. ResponseEntity < String > responseEntity = restTemplate.postForEntity(url, requestEntity, String.class);
  150. body = responseEntity.getBody();
  151. }
  152. catch (Exception e)
  153. {
  154. e.printStackTrace();
  155. log.error("Rest调用异常!!!地址 : " + url + "\n" + "参数 : " + map.toString() + "\n" + "请求头 : " + headerMap.toString(), e);
  156. }
  157. return body;
  158. }
  159. }

SendMailUtils

发送邮件主类

  1. import com.oristand.common.model.MyAuthenticator;
  2. import com.oristand.common.model.SimpleMail;
  3. import org.springframework.stereotype.Component;
  4.  
  5. import javax.activation.DataHandler;
  6. import javax.activation.DataSource;
  7. import javax.activation.FileDataSource;
  8. import javax.mail.*;
  9. import javax.mail.internet.*;
  10. import java.util.Map;
  11. import java.util.Map.Entry;
  12. import java.util.Properties;
  13. import java.util.Set;
  14.  
  15. @Component
  16. public class SendMailUtil {
  17.  
  18. public static boolean sendMail(SimpleMail mailInfo){
  19. String host = mailInfo.getHost();
  20. String port = mailInfo.getPort();
  21. String username = mailInfo.getUserName();
  22. String password = mailInfo.getPassword();
  23. String from = mailInfo.getFrom();
  24. String[] to = mailInfo.getTo();
  25. String[] cc = mailInfo.getCc();
  26. Boolean needAuth = mailInfo.getNeedAuth();
  27. Map<String,String> fileInfo = mailInfo.getFiles();
  28.  
  29. Properties props = new Properties();
  30. props.put("mail.smtp.host", host);
  31. props.put("mail.smtp.port", port);
  32. props.put("mail.smtp.auth", needAuth?"true":"flase");
  33.  
  34. MyAuthenticator auth = null;
  35. if(needAuth){
  36. auth = new MyAuthenticator(username, password);
  37. }
  38.  
  39. Session session = Session.getInstance(props,auth);
  40.  
  41. try {
  42. MimeMessage msg = new MimeMessage(session);
  43. msg.setFrom(new InternetAddress(from));
  44. if(to.length>0){
  45. InternetAddress[] toAddrs = new InternetAddress[to.length];
  46. for(int i=0;i<to.length;i++){
  47. toAddrs[i] = new InternetAddress(to[i]);
  48. }
  49. msg.setRecipients(Message.RecipientType.TO, toAddrs);
  50. }
  51. if(cc!=null && cc.length>0){
  52. InternetAddress[] ccAddrs = new InternetAddress[cc.length];
  53. for(int i=0;i<cc.length;i++){
  54. ccAddrs[i] = new InternetAddress(cc[i]);
  55. }
  56. msg.setRecipients(Message.RecipientType.CC, ccAddrs);
  57. }
  58. msg.setSubject(toChinese(mailInfo.getSubject()));
  59.  
  60. // 创建多重消息
  61. Multipart multipart = new MimeMultipart();
  62.  
  63. // 创建消息部分
  64. BodyPart messageBodyPart = new MimeBodyPart();
  65.  
  66. // 消息
  67. messageBodyPart.setText(mailInfo.getContent());
  68.  
  69. // 设置文本消息部分
  70. multipart.addBodyPart(messageBodyPart);
  71.  
  72. // 附件部分
  73. if(fileInfo!=null && fileInfo.size()>0){
  74. Set<Entry<String, String>> files = fileInfo.entrySet();
  75. for (Entry<String, String> entry : files) {
  76. String filename = entry.getKey();
  77. String filePath = entry.getValue();
  78. messageBodyPart = new MimeBodyPart();
  79. // 设置要发送附件的文件路径
  80. DataSource source = new FileDataSource(filePath);
  81. messageBodyPart.setDataHandler(new DataHandler(source));
  82. // messageBodyPart.setFileName(filename);
  83. // 处理附件名称中文(附带文件路径)乱码问题
  84. messageBodyPart.setFileName(MimeUtility.encodeText(filename));
  85. multipart.addBodyPart(messageBodyPart);
  86. }
  87. }
  88.  
  89. // 发送完整消息
  90. msg.setContent(multipart);
  91.  
  92. Transport.send(msg);
  93. return true;
  94. } catch (Exception e) {
  95. e.printStackTrace();
  96. }
  97. return false;
  98. }
  99.  
  100. public static String toChinese(String text){
  101. try {
  102. text = MimeUtility.encodeText(text, "utf-8", "B");
  103. } catch (Exception e) {
  104. e.printStackTrace();
  105. }
  106. return text;
  107. }
  108. }

获取认证auth类

  1. import javax.mail.Authenticator;
  2. import javax.mail.PasswordAuthentication;
  3.  
  4. public class MyAuthenticator extends Authenticator {
  5. String userName=null;
  6. String password=null;
  7.  
  8. public MyAuthenticator(){
  9. }
  10.  
  11. public MyAuthenticator(String username, String password) {
  12. this.userName = username;
  13. this.password = password;
  14. }
  15. protected PasswordAuthentication getPasswordAuthentication(){
  16. return new PasswordAuthentication(userName, password);
  17. }
  18. }

SimpleMail(发送邮件主类参数)

  1. public class SimpleMail {
  2. private String[] to; //收件人
  3. private String[] cc; //抄送人
  4. private String from = "service7@bulkea.oristand.com"; //发件人
  5. private String host = "smtp.exmail.qq.com";
  6. private String port = "25";
  7. private String userName = "service7@bulkea.oristand.com";
  8. private String password = "Ori20180905";
  9. private String subject;
  10. private String content;
  11. private Boolean needAuth = true;
  12. private Map<String, String> files; //附件
  13.  
  14. public SimpleMail(String[] to, String[] cc, String subject, String content) {
  15. super();
  16. this.to = to;
  17. this.cc = cc;
  18. this.subject = subject;
  19. this.content = content;
  20. }
  21.  
  22. public String[] getTo() {
  23. return to;
  24. }
  25.  
  26. public void setTo(String[] to) {
  27. this.to = to;
  28. }
  29.  
  30. public String getFrom() {
  31. return from;
  32. }
  33.  
  34. public void setFrom(String from) {
  35. this.from = from;
  36. }
  37.  
  38. public String getHost() {
  39. return host;
  40. }
  41.  
  42. public void setHost(String host) {
  43. this.host = host;
  44. }
  45.  
  46. public String getUserName() {
  47. return userName;
  48. }
  49.  
  50. public void setUserName(String userName) {
  51. this.userName = userName;
  52. }
  53.  
  54. public String getPassword() {
  55. return password;
  56. }
  57.  
  58. public void setPassword(String password) {
  59. this.password = password;
  60. }
  61.  
  62. public String getSubject() {
  63. return subject;
  64. }
  65.  
  66. public void setSubject(String subject) {
  67. this.subject = subject;
  68. }
  69.  
  70. public String getContent() {
  71. return content;
  72. }
  73.  
  74. public void setContent(String content) {
  75. this.content = content;
  76. }
  77.  
  78. public Map<String, String> getFiles() {
  79. return files;
  80. }
  81.  
  82. public void setFiles(Map<String, String> files) {
  83. this.files = files;
  84. }
  85.  
  86. public String[] getCc() {
  87. return cc;
  88. }
  89.  
  90. public void setCc(String[] cc) {
  91. this.cc = cc;
  92. }
  93.  
  94. public String getPort() {
  95. return port;
  96. }
  97.  
  98. public void setPort(String port) {
  99. this.port = port;
  100. }
  101.  
  102. public Boolean getNeedAuth() {
  103. return needAuth;
  104. }
  105.  
  106. public void setNeedAuth(Boolean needAuth) {
  107. this.needAuth = needAuth;
  108. }
  109. }

分割List为多个List

  1. import java.util.ArrayList;
  2. import java.util.List;
  3.  
  4. public class SplitListUtil {
  5. public static <T> List<List<T>> split(List<T> sList, int num) {
  6. List<List<T>> eList = new ArrayList<List<T>>();
  7. int size = sList.size();
  8.  
  9. if (sList.size() > num) {
  10. int i = size / num;
  11.  
  12. if ((i * num) < size) {
  13. i = i + 1;
  14. }
  15.  
  16. for (int s = 0; s < i; s++) {
  17. List<T> a = new ArrayList<T>();
  18. int i1 = s * num;
  19. int i2 = num + (s * num);
  20.  
  21. if (i2 > size) {
  22. i2 = size;
  23. }
  24.  
  25. for (int n = i1; n < i2; n++) {
  26. a.add(sList.get(n));
  27. }
  28.  
  29. eList.add(a);
  30. }
  31.  
  32. return eList;
  33. } else {
  34. eList.add(sList);
  35.  
  36. return eList;
  37. }
  38. }
  39. }

静态String池

  1. /**
  2. * 静态 String 池
  3. */
  4. public interface StringPool {
  5. String AMPERSAND = "&";
  6. String AND = "and";
  7. String AT = "@";
  8. String ASTERISK = "*";
  9. String STAR = ASTERISK;
  10. String SLASH = "/";
  11. String BACK_SLASH = "\\";
  12. String DOUBLE_SLASH = "#//";
  13. String COLON = ":";
  14. String COMMA = ",";
  15. String DASH = "-";
  16. String DOLLAR = "$";
  17. String DOT = ".";
  18. String EMPTY = "";
  19. String EMPTY_JSON = "{}";
  20. String EQUALS = "=";
  21. String FALSE = "false";
  22. String HASH = "#";
  23. String HAT = "^";
  24. String LEFT_BRACE = "{";
  25. String LEFT_BRACKET = "(";
  26. String LEFT_CHEV = "<";
  27. String NEWLINE = "\n";
  28. String N = "n";
  29. String NO = "no";
  30. String NULL = "null";
  31. String OFF = "off";
  32. String ON = "on";
  33. String PERCENT = "%";
  34. String PIPE = "|";
  35. String PLUS = "+";
  36. String QUESTION_MARK = "?";
  37. String EXCLAMATION_MARK = "!";
  38. String QUOTE = "\"";
  39. String RETURN = "\r";
  40. String TAB = "\t";
  41. String RIGHT_BRACE = "}";
  42. String RIGHT_BRACKET = ")";
  43. String RIGHT_CHEV = ">";
  44. String SEMICOLON = ";";
  45. String SINGLE_QUOTE = "'";
  46. String BACKTICK = "`";
  47. String SPACE = " ";
  48. String TILDA = "~";
  49. String LEFT_SQ_BRACKET = "[";
  50. String RIGHT_SQ_BRACKET = "]";
  51. String TRUE = "true";
  52. String UNDERSCORE = "_";
  53. String UTF_8 = "UTF-8";
  54. String GBK = "GBK";
  55. String ISO_8859_1 = "ISO-8859-1";
  56. String Y = "y";
  57. String YES = "yes";
  58. String ONE = "1";
  59. String ZERO = "0";
  60. String TWO = "2";
  61. String DOLLAR_LEFT_BRACE = "${";
  62. String UNKNOWN = "unknown";
  63. String UNDEFINED = "undefined";
  64. String GET = "GET";
  65. String POST = "POST";
  66. String COLON_STA = ":*";
  67. }

字符串工具类

  1. package com.oristand.common.util;
  2. import org.springframework.lang.Nullable;
  3. import org.springframework.util.PatternMatchUtils;
  4. import org.springframework.web.util.HtmlUtils;
  5. import java.io.StringReader;
  6. import java.io.StringWriter;
  7. import java.text.MessageFormat;
  8. import java.text.SimpleDateFormat;
  9. import java.util.*;
  10. import java.util.concurrent.ThreadLocalRandom;
  11. import java.util.regex.Matcher;
  12. import java.util.regex.Pattern;
  13. import java.util.stream.Stream;
  14. /**
  15. * 继承自Spring util的工具类,减少jar依赖
  16. *
  17. */
  18. public class StringUtil extends org.springframework.util.StringUtils
  19. {
  20. public static final int INDEX_NOT_FOUND = -1;
  21. //判断是否null或空值,或全部空格
  22. public static boolean isEmpty(Object str)
  23. {
  24. if (str == null || str.toString()
  25. .equals(""))
  26. {
  27. return true;
  28. }
  29. if (str.toString()
  30. .trim()
  31. .equals(""))
  32. {
  33. return true;
  34. }
  35. return false;
  36. }
  37. /**
  38. * 检查 参数String 是否为有意义的字符串<br>
  39. * 不为null,且不为空
  40. *
  41. * @param string
  42. * @return
  43. */
  44. public static boolean isValid(String string)
  45. {
  46. if (string == null || string.isEmpty())
  47. {
  48. return false;
  49. }
  50. else
  51. {
  52. return true;
  53. }
  54. }
  55. /**
  56. * 检查 参数StringBuffer 是否为有意义的字符串<br>
  57. * 不为null,且不为空
  58. *
  59. * @param
  60. * @return
  61. */
  62. public static boolean isValid(StringBuffer sb)
  63. {
  64. if (sb == null || sb.length() == 0)
  65. {
  66. return false;
  67. }
  68. else
  69. {
  70. return true;
  71. }
  72. }
  73. /**
  74. * 检查 参数StringBuilder 是否为有意义的字符串<br>
  75. * 不为null,且不为空
  76. *
  77. * @param
  78. * @return
  79. */
  80. public static boolean isValid(StringBuilder sb)
  81. {
  82. if (sb == null || sb.length() == 0)
  83. {
  84. return false;
  85. }
  86. else
  87. {
  88. return true;
  89. }
  90. }
  91. /**
  92. * 检查 参数Object 是否为有意义的对象<br>
  93. * 不为null,且不为空
  94. *
  95. * @param object
  96. * @return
  97. */
  98. public static boolean isValid(Object object)
  99. {
  100. if (object == null || object.toString()
  101. .length() == 0)
  102. {
  103. return false;
  104. }
  105. else
  106. {
  107. return true;
  108. }
  109. }
  110. /**
  111. * 中文:/[\u4e00-\u9fa5]/
  112. * 日文:/[\u0800-\u4e00]/
  113. * 韩文:/[\uac00-\ud7ff]/
  114. *
  115. * @param str
  116. * @return
  117. */
  118. public static boolean isJapanesChar(String str)
  119. {
  120. boolean temp = false;
  121. Pattern p = Pattern.compile("[ࠀ-一]");
  122. Matcher m = p.matcher(str);
  123. if (m.find())
  124. {
  125. temp = true;
  126. }
  127. return temp;
  128. }
  129. public static String getString(String str)
  130. {
  131. if (str == null || "".equals(str))
  132. {
  133. return "";
  134. }
  135. else
  136. {
  137. return str;
  138. }
  139. }
  140. private static boolean isMatch(String regex, String orginal)
  141. {
  142. if (orginal == null || orginal.trim()
  143. .equals(""))
  144. {
  145. return false;
  146. }
  147. Pattern pattern = Pattern.compile(regex);
  148. Matcher isNum = pattern.matcher(orginal);
  149. return isNum.matches();
  150. }
  151. /**
  152. * 是否是小数
  153. * @param orginal
  154. * @return
  155. */
  156. public static boolean isDecimal(String orginal)
  157. {
  158. return isMatch("[-+]{0,1}\\d+\\.\\d*|[-+]{0,1}\\d*\\.\\d+", orginal);
  159. }
  160. //判断是否null或空值,或全部空格
  161. public static boolean isEmptyOrNull(Object str)
  162. {
  163. if (str == null || str.toString()
  164. .equals("")) return true;
  165. if (str.toString()
  166. .trim()
  167. .equals("")) return true;
  168. if (str.toString()
  169. .trim()
  170. .toUpperCase()
  171. .equals("NULL")) return true;
  172. return false;
  173. }
  174. /**
  175. * 是否是正整数
  176. * @param orginal
  177. * @return
  178. */
  179. public static boolean isPositiveInteger(String orginal)
  180. {
  181. return isMatch("^\\+{0,1}[1-9]\\d*", orginal);
  182. }
  183. /**
  184. * 是否是负整数
  185. * @param orginal
  186. * @return
  187. */
  188. public static boolean isNegativeInteger(String orginal)
  189. {
  190. return isMatch("^-[1-9]\\d*", orginal);
  191. }
  192. /**
  193. * 是否是整数
  194. * @param orginal
  195. * @return
  196. */
  197. public static boolean isWholeNumber(String orginal)
  198. {
  199. return isMatch("[+-]{0,1}0", orginal) || isPositiveInteger(orginal) || isNegativeInteger(orginal);
  200. }
  201. /**
  202. * 是否是实数
  203. * @param orginal
  204. * @return
  205. */
  206. public static boolean isRealNumber(Object orginal)
  207. {
  208. if (isEmptyOrNull(orginal)) return false;
  209. return isWholeNumber(orginal.toString()) || isDecimal(orginal.toString());
  210. }
  211. public static String getNumberValuePro(Object a)
  212. {
  213. if (isEmpty(a))
  214. {
  215. return "0";
  216. }
  217. if (isRealNumber(a))
  218. {
  219. return a.toString();
  220. }
  221. return "0";
  222. }
  223. public static String getStringValue(Object a)
  224. {
  225. if (isEmpty(a))
  226. {
  227. return "";
  228. }
  229. return a.toString();
  230. }
  231. public static String getUsFormatCreateDate(Object obj)
  232. {
  233. SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  234. SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
  235. Date orderDate;
  236. try
  237. {
  238. if (isEmptyOrNull(obj))
  239. {
  240. orderDate = new Date();
  241. }
  242. else
  243. {
  244. orderDate = sdf1.parse(getStringValue(obj));
  245. }
  246. sdf2.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
  247. String orderDateStr = sdf2.format(orderDate);
  248. return orderDateStr;
  249. }
  250. catch (Exception e)
  251. {
  252. e.printStackTrace();
  253. return null;
  254. }
  255. }
  256. /**
  257. * 逗号拼接List元素
  258. * @param list
  259. * @return
  260. */
  261. public static String listToStr(List < String > list)
  262. {
  263. if (list == null || list.size() == 0)
  264. {
  265. return "";
  266. }
  267. StringBuffer sb = new StringBuffer();
  268. for (String t: list)
  269. {
  270. sb.append(String.valueOf(t) + ",");
  271. }
  272. if (sb.length() > 1)
  273. {
  274. sb.deleteCharAt(sb.length() - 1);
  275. }
  276. return sb.toString();
  277. }
  278. /**
  279. * 截取字符串
  280. *
  281. * @param s
  282. * @param maxlength
  283. * @return
  284. */
  285. public static String substringpro(String s, int begin, int maxlength)
  286. {
  287. try
  288. {
  289. int tempcz = s.length() - maxlength; //相差的字节数
  290. if (tempcz <= 0)
  291. {
  292. return s;
  293. }
  294. else
  295. {
  296. return s.substring(begin, maxlength);
  297. }
  298. }
  299. catch (Exception e)
  300. {
  301. return s;
  302. }
  303. }
  304. /**
  305. * Check whether the given {@code CharSequence} contains actual <em>text</em>.
  306. * <p>More specifically, this method returns {@code true} if the
  307. * {@code CharSequence} is not {@code null}, its length is greater than
  308. * 0, and it contains at least one non-whitespace character.
  309. * <pre class="code">
  310. * StringUtil.isBlank(null) = true
  311. * StringUtil.isBlank("") = true
  312. * StringUtil.isBlank(" ") = true
  313. * StringUtil.isBlank("12345") = false
  314. * StringUtil.isBlank(" 12345 ") = false
  315. * </pre>
  316. *
  317. * @param cs the {@code CharSequence} to check (may be {@code null})
  318. * @return {@code true} if the {@code CharSequence} is not {@code null},
  319. * its length is greater than 0, and it does not contain whitespace only
  320. * @see Character#isWhitespace
  321. */
  322. public static boolean isBlank(final CharSequence cs)
  323. {
  324. return !StringUtil.hasText(cs);
  325. }
  326. /**
  327. * <p>Checks if a CharSequence is not empty (""), not null and not whitespace only.</p>
  328. * <pre>
  329. * StringUtil.isNotBlank(null) = false
  330. * StringUtil.isNotBlank("") = false
  331. * StringUtil.isNotBlank(" ") = false
  332. * StringUtil.isNotBlank("bob") = true
  333. * StringUtil.isNotBlank(" bob ") = true
  334. * </pre>
  335. *
  336. * @param cs the CharSequence to check, may be null
  337. * @return {@code true} if the CharSequence is
  338. * not empty and not null and not whitespace
  339. * @see Character#isWhitespace
  340. */
  341. public static boolean isNotBlank(final CharSequence cs)
  342. {
  343. return StringUtil.hasText(cs);
  344. }
  345. /**
  346. * 是否全为 Blank
  347. *
  348. * @param css CharSequence
  349. * @return boolean
  350. */
  351. public static boolean isAllBlank(final CharSequence...css)
  352. {
  353. return Stream.of(css)
  354. .allMatch(StringUtil::isBlank);
  355. }
  356. /**
  357. * 判断一个字符串是否是数字
  358. *
  359. * @param cs the CharSequence to check, may be null
  360. * @return {boolean}
  361. */
  362. public static boolean isNumeric(final CharSequence cs)
  363. {
  364. if (isBlank(cs))
  365. {
  366. return false;
  367. }
  368. for (int i = cs.length(); --i >= 0;)
  369. {
  370. int chr = cs.charAt(i);
  371. if (chr < 48 || chr > 57)
  372. {
  373. return false;
  374. }
  375. }
  376. return true;
  377. }
  378. /**
  379. * 将字符串中特定模式的字符转换成map中对应的值
  380. * <p>
  381. * use: format("my name is ${name}, and i like ${like}!", {"name":"xx", "like": "Java"})
  382. *
  383. * @param message 需要转换的字符串
  384. * @param params 转换所需的键值对集合
  385. * @return 转换后的字符串
  386. */
  387. public static String format(@Nullable String message, @Nullable Map < String, Object > params)
  388. {
  389. // message 为 null 返回空字符串
  390. if (message == null)
  391. {
  392. return StringPool.EMPTY;
  393. }
  394. // 参数为 null 或者为空
  395. if (params == null || params.isEmpty())
  396. {
  397. return message;
  398. }
  399. // 替换变量
  400. StringBuilder sb = new StringBuilder((int)(message.length() * 1.5));
  401. int cursor = 0;
  402. for (int start, end;
  403. (start = message.indexOf(StringPool.DOLLAR_LEFT_BRACE, cursor)) != -1 && (end = message.indexOf(StringPool.RIGHT_BRACE, start)) != -1;)
  404. {
  405. sb.append(message, cursor, start);
  406. String key = message.substring(start + 2, end);
  407. Object value = params.get(StringUtil.trimWhitespace(key));
  408. sb.append(value == null ? StringPool.EMPTY : value);
  409. cursor = end + 1;
  410. }
  411. sb.append(message.substring(cursor));
  412. return sb.toString();
  413. }
  414. /**
  415. * 同 log 格式的 format 规则
  416. * <p>
  417. * use: format("my name is {}, and i like {}!", "xx", "Java")
  418. *
  419. * @param message 需要转换的字符串
  420. * @param arguments 需要替换的变量
  421. * @return 转换后的字符串
  422. */
  423. public static String format(@Nullable String message, @Nullable Object...arguments)
  424. {
  425. // message 为 null 返回空字符串
  426. if (message == null)
  427. {
  428. return StringPool.EMPTY;
  429. }
  430. // 参数为 null 或者为空
  431. if (arguments == null || arguments.length == 0)
  432. {
  433. return message;
  434. }
  435. StringBuilder sb = new StringBuilder((int)(message.length() * 1.5));
  436. int cursor = 0;
  437. int index = 0;
  438. int argsLength = arguments.length;
  439. for (int start, end;
  440. (start = message.indexOf('{', cursor)) != -1 && (end = message.indexOf('}', start)) != -1 && index < argsLength;)
  441. {
  442. sb.append(message, cursor, start);
  443. sb.append(arguments[index]);
  444. cursor = end + 1;
  445. index++;
  446. }
  447. sb.append(message.substring(cursor));
  448. return sb.toString();
  449. }
  450. /**
  451. * Convert a {@code Collection} into a delimited {@code String} (e.g., CSV).
  452. * <p>Useful for {@code toString()} implementations.
  453. *
  454. * @param coll the {@code Collection} to convert
  455. * @return the delimited {@code String}
  456. */
  457. public static String join(Collection < ? > coll)
  458. {
  459. return StringUtil.collectionToCommaDelimitedString(coll);
  460. }
  461. /**
  462. * Convert a {@code Collection} into a delimited {@code String} (e.g. CSV).
  463. * <p>Useful for {@code toString()} implementations.
  464. *
  465. * @param coll the {@code Collection} to convert
  466. * @param delim the delimiter to use (typically a ",")
  467. * @return the delimited {@code String}
  468. */
  469. public static String join(Collection < ? > coll, String delim)
  470. {
  471. return StringUtil.collectionToDelimitedString(coll, delim);
  472. }
  473. /**
  474. * Convert a {@code String} array into a comma delimited {@code String}
  475. * (i.e., CSV).
  476. * <p>Useful for {@code toString()} implementations.
  477. *
  478. * @param arr the array to display
  479. * @return the delimited {@code String}
  480. */
  481. public static String join(Object[] arr)
  482. {
  483. return StringUtil.arrayToCommaDelimitedString(arr);
  484. }
  485. /**
  486. * Convert a {@code String} array into a delimited {@code String} (e.g. CSV).
  487. * <p>Useful for {@code toString()} implementations.
  488. *
  489. * @param arr the array to display
  490. * @param delim the delimiter to use (typically a ",")
  491. * @return the delimited {@code String}
  492. */
  493. public static String join(Object[] arr, String delim)
  494. {
  495. return StringUtil.arrayToDelimitedString(arr, delim);
  496. }
  497. /**
  498. * 字符串是否符合指定的 表达式
  499. *
  500. * <p>
  501. * pattern styles: "xxx*", "*xxx", "*xxx*" and "xxx*yyy"
  502. * </p>
  503. *
  504. * @param pattern 表达式
  505. * @param str 字符串
  506. * @return 是否匹配
  507. */
  508. public static boolean simpleMatch(@Nullable String pattern, @Nullable String str)
  509. {
  510. return PatternMatchUtils.simpleMatch(pattern, str);
  511. }
  512. /**
  513. * 字符串是否符合指定的 表达式
  514. *
  515. * <p>
  516. * pattern styles: "xxx*", "*xxx", "*xxx*" and "xxx*yyy"
  517. * </p>
  518. *
  519. * @param patterns 表达式 数组
  520. * @param str 字符串
  521. * @return 是否匹配
  522. */
  523. public static boolean simpleMatch(@Nullable String[] patterns, String str)
  524. {
  525. return PatternMatchUtils.simpleMatch(patterns, str);
  526. }
  527. /**
  528. * 生成uuid
  529. *
  530. * @return UUID
  531. */
  532. public static String randomUUID()
  533. {
  534. ThreadLocalRandom random = ThreadLocalRandom.current();
  535. return new UUID(random.nextLong(), random.nextLong())
  536. .toString()
  537. .replace(StringPool.DASH, StringPool.EMPTY);
  538. }
  539. /**
  540. * 转义HTML用于安全过滤
  541. *
  542. * @param html html
  543. * @return {String}
  544. */
  545. public static String escapeHtml(String html)
  546. {
  547. return StringUtil.isBlank(html) ? StringPool.EMPTY : HtmlUtils.htmlEscape(html);
  548. }
  549. /**
  550. * 清理字符串,清理出某些不可见字符
  551. *
  552. * @param txt 字符串
  553. * @return {String}
  554. */
  555. public static String cleanChars(String txt)
  556. {
  557. return txt.replaceAll("[  `·•�\\f\\t\\v\\s]", "");
  558. }
  559. private static final String S_INT = "0123456789";
  560. private static final String S_STR = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  561. private static final String S_ALL = S_INT + S_STR;
  562. /**
  563. * 有序的格式化文本,使用{number}做为占位符<br>
  564. * 例:<br>
  565. * 通常使用:format("this is {0} for {1}", "a", "b") =》 this is a for b<br>
  566. *
  567. * @param pattern 文本格式
  568. * @param arguments 参数
  569. * @return 格式化后的文本
  570. */
  571. public static String indexedFormat(CharSequence pattern, Object...arguments)
  572. {
  573. return MessageFormat.format(pattern.toString(), arguments);
  574. }
  575. /**
  576. * 切分字符串,不去除切分后每个元素两边的空白符,不去除空白项
  577. *
  578. * @param str 被切分的字符串
  579. * @param separator 分隔符字符
  580. * @param limit 限制分片数,-1不限制
  581. * @return 切分后的集合
  582. */
  583. public static List < String > split(CharSequence str, char separator, int limit)
  584. {
  585. return split(str, separator, limit, false, false);
  586. }
  587. /**
  588. * 分割 字符串 删除常见 空白符
  589. *
  590. * @param str 字符串
  591. * @param delimiter 分割符
  592. * @return 字符串数组
  593. */
  594. public static String[] splitTrim(@Nullable String str, @Nullable String delimiter)
  595. {
  596. return StringUtil.delimitedListToStringArray(str, delimiter, " \t\n\n\f");
  597. }
  598. /**
  599. * 切分字符串,去除切分后每个元素两边的空白符,去除空白项
  600. *
  601. * @param str 被切分的字符串
  602. * @param separator 分隔符字符
  603. * @return 切分后的集合
  604. * @since 3.1.2
  605. */
  606. public static List < String > splitTrim(CharSequence str, char separator)
  607. {
  608. return splitTrim(str, separator, -1);
  609. }
  610. /**
  611. * 切分字符串,去除切分后每个元素两边的空白符,去除空白项
  612. *
  613. * @param str 被切分的字符串
  614. * @param separator 分隔符字符
  615. * @return 切分后的集合
  616. * @since 3.2.0
  617. */
  618. public static List < String > splitTrim(CharSequence str, CharSequence separator)
  619. {
  620. return splitTrim(str, separator, -1);
  621. }
  622. /**
  623. * 切分字符串,去除切分后每个元素两边的空白符,去除空白项
  624. *
  625. * @param str 被切分的字符串
  626. * @param separator 分隔符字符
  627. * @param limit 限制分片数,-1不限制
  628. * @return 切分后的集合
  629. * @since 3.1.0
  630. */
  631. public static List < String > splitTrim(CharSequence str, char separator, int limit)
  632. {
  633. return split(str, separator, limit, true, true);
  634. }
  635. /**
  636. * 切分字符串,去除切分后每个元素两边的空白符,去除空白项
  637. *
  638. * @param str 被切分的字符串
  639. * @param separator 分隔符字符
  640. * @param limit 限制分片数,-1不限制
  641. * @return 切分后的集合
  642. * @since 3.2.0
  643. */
  644. public static List < String > splitTrim(CharSequence str, CharSequence separator, int limit)
  645. {
  646. return split(str, separator, limit, true, true);
  647. }
  648. /**
  649. * 切分字符串,不限制分片数量
  650. *
  651. * @param str 被切分的字符串
  652. * @param separator 分隔符字符
  653. * @param isTrim 是否去除切分字符串后每个元素两边的空格
  654. * @param ignoreEmpty 是否忽略空串
  655. * @return 切分后的集合
  656. * @since 3.0.8
  657. */
  658. public static List < String > split(CharSequence str, char separator, boolean isTrim, boolean ignoreEmpty)
  659. {
  660. return split(str, separator, 0, isTrim, ignoreEmpty);
  661. }
  662. /**
  663. * 切分字符串
  664. *
  665. * @param str 被切分的字符串
  666. * @param separator 分隔符字符
  667. * @param limit 限制分片数,-1不限制
  668. * @param isTrim 是否去除切分字符串后每个元素两边的空格
  669. * @param ignoreEmpty 是否忽略空串
  670. * @return 切分后的集合
  671. * @since 3.0.8
  672. */
  673. public static List < String > split(CharSequence str, char separator, int limit, boolean isTrim, boolean ignoreEmpty)
  674. {
  675. if (null == str)
  676. {
  677. return new ArrayList < > (0);
  678. }
  679. return StrSpliter.split(str.toString(), separator, limit, isTrim, ignoreEmpty);
  680. }
  681. /**
  682. * 切分字符串
  683. *
  684. * @param str 被切分的字符串
  685. * @param separator 分隔符字符
  686. * @param limit 限制分片数,-1不限制
  687. * @param isTrim 是否去除切分字符串后每个元素两边的空格
  688. * @param ignoreEmpty 是否忽略空串
  689. * @return 切分后的集合
  690. * @since 3.2.0
  691. */
  692. public static List < String > split(CharSequence str, CharSequence separator, int limit, boolean isTrim, boolean ignoreEmpty)
  693. {
  694. if (null == str)
  695. {
  696. return new ArrayList < > (0);
  697. }
  698. final String separatorStr = (null == separator) ? null : separator.toString();
  699. return StrSpliter.split(str.toString(), separatorStr, limit, isTrim, ignoreEmpty);
  700. }
  701. /**
  702. * 切分字符串
  703. *
  704. * @param str 被切分的字符串
  705. * @param separator 分隔符
  706. * @return 字符串
  707. */
  708. public static String[] split(CharSequence str, CharSequence separator)
  709. {
  710. if (str == null)
  711. {
  712. return new String[]
  713. {};
  714. }
  715. final String separatorStr = (null == separator) ? null : separator.toString();
  716. return StrSpliter.splitToArray(str.toString(), separatorStr, 0, false, false);
  717. }
  718. /**
  719. * 根据给定长度,将给定字符串截取为多个部分
  720. *
  721. * @param str 字符串
  722. * @param len 每一个小节的长度
  723. * @return 截取后的字符串数组
  724. * @see StrSpliter#splitByLength(String, int)
  725. */
  726. public static String[] split(CharSequence str, int len)
  727. {
  728. if (null == str)
  729. {
  730. return new String[]
  731. {};
  732. }
  733. return StrSpliter.splitByLength(str.toString(), len);
  734. }
  735. /**
  736. * 指定字符是否在字符串中出现过
  737. *
  738. * @param str 字符串
  739. * @param searchChar 被查找的字符
  740. * @return 是否包含
  741. * @since 3.1.2
  742. */
  743. public static boolean contains(CharSequence str, char searchChar)
  744. {
  745. return indexOf(str, searchChar) > -1;
  746. }
  747. /**
  748. * 是否包含特定字符,忽略大小写,如果给定两个参数都为<code>null</code>,返回true
  749. *
  750. * @param str 被检测字符串
  751. * @param testStr 被测试是否包含的字符串
  752. * @return 是否包含
  753. */
  754. public static boolean containsIgnoreCase(CharSequence str, CharSequence testStr)
  755. {
  756. if (null == str)
  757. {
  758. // 如果被监测字符串和
  759. return null == testStr;
  760. }
  761. return str.toString()
  762. .toLowerCase()
  763. .contains(testStr.toString()
  764. .toLowerCase());
  765. }
  766. /**
  767. * 改进JDK subString<br>
  768. * index从0开始计算,最后一个字符为-1<br>
  769. * 如果from和to位置一样,返回 "" <br>
  770. * 如果from或to为负数,则按照length从后向前数位置,如果绝对值大于字符串长度,则from归到0,to归到length<br>
  771. * 如果经过修正的index中from大于to,则互换from和to example: <br>
  772. * abcdefgh 2 3 =》 c <br>
  773. * abcdefgh 2 -3 =》 cde <br>
  774. *
  775. * @param str String
  776. * @param fromIndex 开始的index(包括)
  777. * @param toIndex 结束的index(不包括)
  778. * @return 字串
  779. */
  780. public static String sub(CharSequence str, int fromIndex, int toIndex)
  781. {
  782. if (isEmpty(str))
  783. {
  784. return StringPool.EMPTY;
  785. }
  786. int len = str.length();
  787. if (fromIndex < 0)
  788. {
  789. fromIndex = len + fromIndex;
  790. if (fromIndex < 0)
  791. {
  792. fromIndex = 0;
  793. }
  794. }
  795. else if (fromIndex > len)
  796. {
  797. fromIndex = len;
  798. }
  799. if (toIndex < 0)
  800. {
  801. toIndex = len + toIndex;
  802. if (toIndex < 0)
  803. {
  804. toIndex = len;
  805. }
  806. }
  807. else if (toIndex > len)
  808. {
  809. toIndex = len;
  810. }
  811. if (toIndex < fromIndex)
  812. {
  813. int tmp = fromIndex;
  814. fromIndex = toIndex;
  815. toIndex = tmp;
  816. }
  817. if (fromIndex == toIndex)
  818. {
  819. return StringPool.EMPTY;
  820. }
  821. return str.toString()
  822. .substring(fromIndex, toIndex);
  823. }
  824. /**
  825. * 截取分隔字符串之前的字符串,不包括分隔字符串<br>
  826. * 如果给定的字符串为空串(null或"")或者分隔字符串为null,返回原字符串<br>
  827. * 如果分隔字符串为空串"",则返回空串,如果分隔字符串未找到,返回原字符串
  828. * <p>
  829. * 栗子:
  830. *
  831. * <pre>
  832. * StringUtil.subBefore(null, *) = null
  833. * StringUtil.subBefore("", *) = ""
  834. * StringUtil.subBefore("abc", "a") = ""
  835. * StringUtil.subBefore("abcba", "b") = "a"
  836. * StringUtil.subBefore("abc", "c") = "ab"
  837. * StringUtil.subBefore("abc", "d") = "abc"
  838. * StringUtil.subBefore("abc", "") = ""
  839. * StringUtil.subBefore("abc", null) = "abc"
  840. * </pre>
  841. *
  842. * @param string 被查找的字符串
  843. * @param separator 分隔字符串(不包括)
  844. * @param isLastSeparator 是否查找最后一个分隔字符串(多次出现分隔字符串时选取最后一个),true为选取最后一个
  845. * @return 切割后的字符串
  846. * @since 3.1.1
  847. */
  848. public static String subBefore(CharSequence string, CharSequence separator, boolean isLastSeparator)
  849. {
  850. if (isEmpty(string) || separator == null)
  851. {
  852. return null == string ? null : string.toString();
  853. }
  854. final String str = string.toString();
  855. final String sep = separator.toString();
  856. if (sep.isEmpty())
  857. {
  858. return StringPool.EMPTY;
  859. }
  860. final int pos = isLastSeparator ? str.lastIndexOf(sep) : str.indexOf(sep);
  861. if (pos == INDEX_NOT_FOUND)
  862. {
  863. return str;
  864. }
  865. return str.substring(0, pos);
  866. }
  867. /**
  868. * 截取分隔字符串之后的字符串,不包括分隔字符串<br>
  869. * 如果给定的字符串为空串(null或""),返回原字符串<br>
  870. * 如果分隔字符串为空串(null或""),则返回空串,如果分隔字符串未找到,返回空串
  871. * <p>
  872. * 栗子:
  873. *
  874. * <pre>
  875. * StringUtil.subAfter(null, *) = null
  876. * StringUtil.subAfter("", *) = ""
  877. * StringUtil.subAfter(*, null) = ""
  878. * StringUtil.subAfter("abc", "a") = "bc"
  879. * StringUtil.subAfter("abcba", "b") = "cba"
  880. * StringUtil.subAfter("abc", "c") = ""
  881. * StringUtil.subAfter("abc", "d") = ""
  882. * StringUtil.subAfter("abc", "") = "abc"
  883. * </pre>
  884. *
  885. * @param string 被查找的字符串
  886. * @param separator 分隔字符串(不包括)
  887. * @param isLastSeparator 是否查找最后一个分隔字符串(多次出现分隔字符串时选取最后一个),true为选取最后一个
  888. * @return 切割后的字符串
  889. * @since 3.1.1
  890. */
  891. public static String subAfter(CharSequence string, CharSequence separator, boolean isLastSeparator)
  892. {
  893. if (isEmpty(string))
  894. {
  895. return null == string ? null : string.toString();
  896. }
  897. if (separator == null)
  898. {
  899. return StringPool.EMPTY;
  900. }
  901. final String str = string.toString();
  902. final String sep = separator.toString();
  903. final int pos = isLastSeparator ? str.lastIndexOf(sep) : str.indexOf(sep);
  904. if (pos == INDEX_NOT_FOUND)
  905. {
  906. return StringPool.EMPTY;
  907. }
  908. return str.substring(pos + separator.length());
  909. }
  910. /**
  911. * 截取指定字符串中间部分,不包括标识字符串<br>
  912. * <p>
  913. * 栗子:
  914. *
  915. * <pre>
  916. * StringUtil.subBetween("wx[b]yz", "[", "]") = "b"
  917. * StringUtil.subBetween(null, *, *) = null
  918. * StringUtil.subBetween(*, null, *) = null
  919. * StringUtil.subBetween(*, *, null) = null
  920. * StringUtil.subBetween("", "", "") = ""
  921. * StringUtil.subBetween("", "", "]") = null
  922. * StringUtil.subBetween("", "[", "]") = null
  923. * StringUtil.subBetween("yabcz", "", "") = ""
  924. * StringUtil.subBetween("yabcz", "y", "z") = "abc"
  925. * StringUtil.subBetween("yabczyabcz", "y", "z") = "abc"
  926. * </pre>
  927. *
  928. * @param str 被切割的字符串
  929. * @param before 截取开始的字符串标识
  930. * @param after 截取到的字符串标识
  931. * @return 截取后的字符串
  932. * @since 3.1.1
  933. */
  934. public static String subBetween(CharSequence str, CharSequence before, CharSequence after)
  935. {
  936. if (str == null || before == null || after == null)
  937. {
  938. return null;
  939. }
  940. final String str2 = str.toString();
  941. final String before2 = before.toString();
  942. final String after2 = after.toString();
  943. final int start = str2.indexOf(before2);
  944. if (start != INDEX_NOT_FOUND)
  945. {
  946. final int end = str2.indexOf(after2, start + before2.length());
  947. if (end != INDEX_NOT_FOUND)
  948. {
  949. return str2.substring(start + before2.length(), end);
  950. }
  951. }
  952. return null;
  953. }
  954. /**
  955. * 截取指定字符串中间部分,不包括标识字符串<br>
  956. * <p>
  957. * 栗子:
  958. *
  959. * <pre>
  960. * StringUtil.subBetween(null, *) = null
  961. * StringUtil.subBetween("", "") = ""
  962. * StringUtil.subBetween("", "tag") = null
  963. * StringUtil.subBetween("tagabctag", null) = null
  964. * StringUtil.subBetween("tagabctag", "") = ""
  965. * StringUtil.subBetween("tagabctag", "tag") = "abc"
  966. * </pre>
  967. *
  968. * @param str 被切割的字符串
  969. * @param beforeAndAfter 截取开始和结束的字符串标识
  970. * @return 截取后的字符串
  971. * @since 3.1.1
  972. */
  973. public static String subBetween(CharSequence str, CharSequence beforeAndAfter)
  974. {
  975. return subBetween(str, beforeAndAfter, beforeAndAfter);
  976. }
  977. /**
  978. * 去掉指定前缀
  979. *
  980. * @param str 字符串
  981. * @param prefix 前缀
  982. * @return 切掉后的字符串,若前缀不是 preffix, 返回原字符串
  983. */
  984. public static String removePrefix(CharSequence str, CharSequence prefix)
  985. {
  986. if (isEmpty(str) || isEmpty(prefix))
  987. {
  988. return StringPool.EMPTY;
  989. }
  990. final String str2 = str.toString();
  991. if (str2.startsWith(prefix.toString()))
  992. {
  993. return subSuf(str2, prefix.length());
  994. }
  995. return str2;
  996. }
  997. /**
  998. * 忽略大小写去掉指定前缀
  999. *
  1000. * @param str 字符串
  1001. * @param prefix 前缀
  1002. * @return 切掉后的字符串,若前缀不是 prefix, 返回原字符串
  1003. */
  1004. public static String removePrefixIgnoreCase(CharSequence str, CharSequence prefix)
  1005. {
  1006. if (isEmpty(str) || isEmpty(prefix))
  1007. {
  1008. return StringPool.EMPTY;
  1009. }
  1010. final String str2 = str.toString();
  1011. if (str2.toLowerCase()
  1012. .startsWith(prefix.toString()
  1013. .toLowerCase()))
  1014. {
  1015. return subSuf(str2, prefix.length());
  1016. }
  1017. return str2;
  1018. }
  1019. /**
  1020. * 去掉指定后缀
  1021. *
  1022. * @param str 字符串
  1023. * @param suffix 后缀
  1024. * @return 切掉后的字符串,若后缀不是 suffix, 返回原字符串
  1025. */
  1026. public static String removeSuffix(CharSequence str, CharSequence suffix)
  1027. {
  1028. if (isEmpty(str) || isEmpty(suffix))
  1029. {
  1030. return StringPool.EMPTY;
  1031. }
  1032. final String str2 = str.toString();
  1033. if (str2.endsWith(suffix.toString()))
  1034. {
  1035. return subPre(str2, str2.length() - suffix.length());
  1036. }
  1037. return str2;
  1038. }
  1039. /**
  1040. * 去掉指定后缀,并小写首字母
  1041. *
  1042. * @param str 字符串
  1043. * @param suffix 后缀
  1044. * @return 切掉后的字符串,若后缀不是 suffix, 返回原字符串
  1045. */
  1046. public static String removeSufAndLowerFirst(CharSequence str, CharSequence suffix)
  1047. {
  1048. return firstCharToLower(removeSuffix(str, suffix));
  1049. }
  1050. /**
  1051. * 忽略大小写去掉指定后缀
  1052. *
  1053. * @param str 字符串
  1054. * @param suffix 后缀
  1055. * @return 切掉后的字符串,若后缀不是 suffix, 返回原字符串
  1056. */
  1057. public static String removeSuffixIgnoreCase(CharSequence str, CharSequence suffix)
  1058. {
  1059. if (isEmpty(str) || isEmpty(suffix))
  1060. {
  1061. return StringPool.EMPTY;
  1062. }
  1063. final String str2 = str.toString();
  1064. if (str2.toLowerCase()
  1065. .endsWith(suffix.toString()
  1066. .toLowerCase()))
  1067. {
  1068. return subPre(str2, str2.length() - suffix.length());
  1069. }
  1070. return str2;
  1071. }
  1072. /**
  1073. * 首字母变小写
  1074. *
  1075. * @param str 字符串
  1076. * @return {String}
  1077. */
  1078. public static String firstCharToLower(String str)
  1079. {
  1080. char firstChar = str.charAt(0);
  1081. if (firstChar >= CharPool.UPPER_A && firstChar <= CharPool.UPPER_Z)
  1082. {
  1083. char[] arr = str.toCharArray();
  1084. arr[0] += CharPool.LOWER_A - CharPool.UPPER_A;
  1085. return new String(arr);
  1086. }
  1087. return str;
  1088. }
  1089. /**
  1090. * 首字母变大写
  1091. *
  1092. * @param str 字符串
  1093. * @return {String}
  1094. */
  1095. public static String firstCharToUpper(String str)
  1096. {
  1097. char firstChar = str.charAt(0);
  1098. if (firstChar >= CharPool.LOWER_A && firstChar <= CharPool.LOWER_Z)
  1099. {
  1100. char[] arr = str.toCharArray();
  1101. arr[0] -= CharPool.LOWER_A - CharPool.UPPER_A;
  1102. return new String(arr);
  1103. }
  1104. return str;
  1105. }
  1106. /**
  1107. * 切割指定位置之前部分的字符串
  1108. *
  1109. * @param string 字符串
  1110. * @param toIndex 切割到的位置(不包括)
  1111. * @return 切割后的剩余的前半部分字符串
  1112. */
  1113. public static String subPre(CharSequence string, int toIndex)
  1114. {
  1115. return sub(string, 0, toIndex);
  1116. }
  1117. /**
  1118. * 切割指定位置之后部分的字符串
  1119. *
  1120. * @param string 字符串
  1121. * @param fromIndex 切割开始的位置(包括)
  1122. * @return 切割后后剩余的后半部分字符串
  1123. */
  1124. public static String subSuf(CharSequence string, int fromIndex)
  1125. {
  1126. if (isEmpty(string))
  1127. {
  1128. return null;
  1129. }
  1130. return sub(string, fromIndex, string.length());
  1131. }
  1132. /**
  1133. * 指定范围内查找指定字符
  1134. *
  1135. * @param str 字符串
  1136. * @param searchChar 被查找的字符
  1137. * @return 位置
  1138. */
  1139. public static int indexOf(final CharSequence str, char searchChar)
  1140. {
  1141. return indexOf(str, searchChar, 0);
  1142. }
  1143. /**
  1144. * 指定范围内查找指定字符
  1145. *
  1146. * @param str 字符串
  1147. * @param searchChar 被查找的字符
  1148. * @param start 起始位置,如果小于0,从0开始查找
  1149. * @return 位置
  1150. */
  1151. public static int indexOf(final CharSequence str, char searchChar, int start)
  1152. {
  1153. if (str instanceof String)
  1154. {
  1155. return ((String) str)
  1156. .indexOf(searchChar, start);
  1157. }
  1158. else
  1159. {
  1160. return indexOf(str, searchChar, start, -1);
  1161. }
  1162. }
  1163. /**
  1164. * 指定范围内查找指定字符
  1165. *
  1166. * @param str 字符串
  1167. * @param searchChar 被查找的字符
  1168. * @param start 起始位置,如果小于0,从0开始查找
  1169. * @param end 终止位置,如果超过str.length()则默认查找到字符串末尾
  1170. * @return 位置
  1171. */
  1172. public static int indexOf(final CharSequence str, char searchChar, int start, int end)
  1173. {
  1174. final int len = str.length();
  1175. if (start < 0 || start > len)
  1176. {
  1177. start = 0;
  1178. }
  1179. if (end > len || end < 0)
  1180. {
  1181. end = len;
  1182. }
  1183. for (int i = start; i < end; i++)
  1184. {
  1185. if (str.charAt(i) == searchChar)
  1186. {
  1187. return i;
  1188. }
  1189. }
  1190. return -1;
  1191. }
  1192. /**
  1193. * 指定范围内查找字符串,忽略大小写<br>
  1194. *
  1195. * <pre>
  1196. * StringUtil.indexOfIgnoreCase(null, *, *) = -1
  1197. * StringUtil.indexOfIgnoreCase(*, null, *) = -1
  1198. * StringUtil.indexOfIgnoreCase("", "", 0) = 0
  1199. * StringUtil.indexOfIgnoreCase("aabaabaa", "A", 0) = 0
  1200. * StringUtil.indexOfIgnoreCase("aabaabaa", "B", 0) = 2
  1201. * StringUtil.indexOfIgnoreCase("aabaabaa", "AB", 0) = 1
  1202. * StringUtil.indexOfIgnoreCase("aabaabaa", "B", 3) = 5
  1203. * StringUtil.indexOfIgnoreCase("aabaabaa", "B", 9) = -1
  1204. * StringUtil.indexOfIgnoreCase("aabaabaa", "B", -1) = 2
  1205. * StringUtil.indexOfIgnoreCase("aabaabaa", "", 2) = 2
  1206. * StringUtil.indexOfIgnoreCase("abc", "", 9) = -1
  1207. * </pre>
  1208. *
  1209. * @param str 字符串
  1210. * @param searchStr 需要查找位置的字符串
  1211. * @return 位置
  1212. * @since 3.2.1
  1213. */
  1214. public static int indexOfIgnoreCase(final CharSequence str, final CharSequence searchStr)
  1215. {
  1216. return indexOfIgnoreCase(str, searchStr, 0);
  1217. }
  1218. /**
  1219. * 指定范围内查找字符串
  1220. *
  1221. * <pre>
  1222. * StringUtil.indexOfIgnoreCase(null, *, *) = -1
  1223. * StringUtil.indexOfIgnoreCase(*, null, *) = -1
  1224. * StringUtil.indexOfIgnoreCase("", "", 0) = 0
  1225. * StringUtil.indexOfIgnoreCase("aabaabaa", "A", 0) = 0
  1226. * StringUtil.indexOfIgnoreCase("aabaabaa", "B", 0) = 2
  1227. * StringUtil.indexOfIgnoreCase("aabaabaa", "AB", 0) = 1
  1228. * StringUtil.indexOfIgnoreCase("aabaabaa", "B", 3) = 5
  1229. * StringUtil.indexOfIgnoreCase("aabaabaa", "B", 9) = -1
  1230. * StringUtil.indexOfIgnoreCase("aabaabaa", "B", -1) = 2
  1231. * StringUtil.indexOfIgnoreCase("aabaabaa", "", 2) = 2
  1232. * StringUtil.indexOfIgnoreCase("abc", "", 9) = -1
  1233. * </pre>
  1234. *
  1235. * @param str 字符串
  1236. * @param searchStr 需要查找位置的字符串
  1237. * @param fromIndex 起始位置
  1238. * @return 位置
  1239. * @since 3.2.1
  1240. */
  1241. public static int indexOfIgnoreCase(final CharSequence str, final CharSequence searchStr, int fromIndex)
  1242. {
  1243. return indexOf(str, searchStr, fromIndex, true);
  1244. }
  1245. /**
  1246. * 指定范围内反向查找字符串
  1247. *
  1248. * @param str 字符串
  1249. * @param searchStr 需要查找位置的字符串
  1250. * @param fromIndex 起始位置
  1251. * @param ignoreCase 是否忽略大小写
  1252. * @return 位置
  1253. * @since 3.2.1
  1254. */
  1255. public static int indexOf(final CharSequence str, CharSequence searchStr, int fromIndex, boolean ignoreCase)
  1256. {
  1257. if (str == null || searchStr == null)
  1258. {
  1259. return INDEX_NOT_FOUND;
  1260. }
  1261. if (fromIndex < 0)
  1262. {
  1263. fromIndex = 0;
  1264. }
  1265. final int endLimit = str.length() - searchStr.length() + 1;
  1266. if (fromIndex > endLimit)
  1267. {
  1268. return INDEX_NOT_FOUND;
  1269. }
  1270. if (searchStr.length() == 0)
  1271. {
  1272. return fromIndex;
  1273. }
  1274. if (false == ignoreCase)
  1275. {
  1276. // 不忽略大小写调用JDK方法
  1277. return str.toString()
  1278. .indexOf(searchStr.toString(), fromIndex);
  1279. }
  1280. for (int i = fromIndex; i < endLimit; i++)
  1281. {
  1282. if (isSubEquals(str, i, searchStr, 0, searchStr.length(), true))
  1283. {
  1284. return i;
  1285. }
  1286. }
  1287. return INDEX_NOT_FOUND;
  1288. }
  1289. /**
  1290. * 指定范围内查找字符串,忽略大小写<br>
  1291. *
  1292. * @param str 字符串
  1293. * @param searchStr 需要查找位置的字符串
  1294. * @return 位置
  1295. * @since 3.2.1
  1296. */
  1297. public static int lastIndexOfIgnoreCase(final CharSequence str, final CharSequence searchStr)
  1298. {
  1299. return lastIndexOfIgnoreCase(str, searchStr, str.length());
  1300. }
  1301. /**
  1302. * 指定范围内查找字符串,忽略大小写<br>
  1303. *
  1304. * @param str 字符串
  1305. * @param searchStr 需要查找位置的字符串
  1306. * @param fromIndex 起始位置,从后往前计数
  1307. * @return 位置
  1308. * @since 3.2.1
  1309. */
  1310. public static int lastIndexOfIgnoreCase(final CharSequence str, final CharSequence searchStr, int fromIndex)
  1311. {
  1312. return lastIndexOf(str, searchStr, fromIndex, true);
  1313. }
  1314. /**
  1315. * 指定范围内查找字符串<br>
  1316. *
  1317. * @param str 字符串
  1318. * @param searchStr 需要查找位置的字符串
  1319. * @param fromIndex 起始位置,从后往前计数
  1320. * @param ignoreCase 是否忽略大小写
  1321. * @return 位置
  1322. * @since 3.2.1
  1323. */
  1324. public static int lastIndexOf(final CharSequence str, final CharSequence searchStr, int fromIndex, boolean ignoreCase)
  1325. {
  1326. if (str == null || searchStr == null)
  1327. {
  1328. return INDEX_NOT_FOUND;
  1329. }
  1330. if (fromIndex < 0)
  1331. {
  1332. fromIndex = 0;
  1333. }
  1334. fromIndex = Math.min(fromIndex, str.length());
  1335. if (searchStr.length() == 0)
  1336. {
  1337. return fromIndex;
  1338. }
  1339. if (!ignoreCase)
  1340. {
  1341. // 不忽略大小写调用JDK方法
  1342. return str.toString()
  1343. .lastIndexOf(searchStr.toString(), fromIndex);
  1344. }
  1345. for (int i = fromIndex; i > 0; i--)
  1346. {
  1347. if (isSubEquals(str, i, searchStr, 0, searchStr.length(), true))
  1348. {
  1349. return i;
  1350. }
  1351. }
  1352. return INDEX_NOT_FOUND;
  1353. }
  1354. /**
  1355. * 返回字符串 searchStr 在字符串 str 中第 ordinal 次出现的位置。<br>
  1356. * 此方法来自:Apache-Commons-Lang
  1357. * <p>
  1358. * 栗子(*代表任意字符):
  1359. *
  1360. * <pre>
  1361. * StringUtil.ordinalIndexOf(null, *, *) = -1
  1362. * StringUtil.ordinalIndexOf(*, null, *) = -1
  1363. * StringUtil.ordinalIndexOf("", "", *) = 0
  1364. * StringUtil.ordinalIndexOf("aabaabaa", "a", 1) = 0
  1365. * StringUtil.ordinalIndexOf("aabaabaa", "a", 2) = 1
  1366. * StringUtil.ordinalIndexOf("aabaabaa", "b", 1) = 2
  1367. * StringUtil.ordinalIndexOf("aabaabaa", "b", 2) = 5
  1368. * StringUtil.ordinalIndexOf("aabaabaa", "ab", 1) = 1
  1369. * StringUtil.ordinalIndexOf("aabaabaa", "ab", 2) = 4
  1370. * StringUtil.ordinalIndexOf("aabaabaa", "", 1) = 0
  1371. * StringUtil.ordinalIndexOf("aabaabaa", "", 2) = 0
  1372. * </pre>
  1373. *
  1374. * @param str 被检查的字符串,可以为null
  1375. * @param searchStr 被查找的字符串,可以为null
  1376. * @param ordinal 第几次出现的位置
  1377. * @return 查找到的位置
  1378. * @since 3.2.3
  1379. */
  1380. public static int ordinalIndexOf(String str, String searchStr, int ordinal)
  1381. {
  1382. if (str == null || searchStr == null || ordinal <= 0)
  1383. {
  1384. return INDEX_NOT_FOUND;
  1385. }
  1386. if (searchStr.length() == 0)
  1387. {
  1388. return 0;
  1389. }
  1390. int found = 0;
  1391. int index = INDEX_NOT_FOUND;
  1392. do {
  1393. index = str.indexOf(searchStr, index + 1);
  1394. if (index < 0)
  1395. {
  1396. return index;
  1397. }
  1398. found++;
  1399. } while (found < ordinal);
  1400. return index;
  1401. }
  1402. /**
  1403. * 截取两个字符串的不同部分(长度一致),判断截取的子串是否相同<br>
  1404. * 任意一个字符串为null返回false
  1405. *
  1406. * @param str1 第一个字符串
  1407. * @param start1 第一个字符串开始的位置
  1408. * @param str2 第二个字符串
  1409. * @param start2 第二个字符串开始的位置
  1410. * @param length 截取长度
  1411. * @param ignoreCase 是否忽略大小写
  1412. * @return 子串是否相同
  1413. * @since 3.2.1
  1414. */
  1415. public static boolean isSubEquals(CharSequence str1, int start1, CharSequence str2, int start2, int length, boolean ignoreCase)
  1416. {
  1417. if (null == str1 || null == str2)
  1418. {
  1419. return false;
  1420. }
  1421. return str1.toString()
  1422. .regionMatches(ignoreCase, start1, str2.toString(), start2, length);
  1423. }
  1424. /**
  1425. * 比较两个字符串(大小写敏感)。
  1426. *
  1427. * <pre>
  1428. * equalsIgnoreCase(null, null) = true
  1429. * equalsIgnoreCase(null, &quot;abc&quot;) = false
  1430. * equalsIgnoreCase(&quot;abc&quot;, null) = false
  1431. * equalsIgnoreCase(&quot;abc&quot;, &quot;abc&quot;) = true
  1432. * equalsIgnoreCase(&quot;abc&quot;, &quot;ABC&quot;) = true
  1433. * </pre>
  1434. *
  1435. * @param str1 要比较的字符串1
  1436. * @param str2 要比较的字符串2
  1437. * @return 如果两个字符串相同,或者都是<code>null</code>,则返回<code>true</code>
  1438. */
  1439. public static boolean equals(CharSequence str1, CharSequence str2)
  1440. {
  1441. return equals(str1, str2, false);
  1442. }
  1443. /**
  1444. * 比较两个字符串(大小写不敏感)。
  1445. *
  1446. * <pre>
  1447. * equalsIgnoreCase(null, null) = true
  1448. * equalsIgnoreCase(null, &quot;abc&quot;) = false
  1449. * equalsIgnoreCase(&quot;abc&quot;, null) = false
  1450. * equalsIgnoreCase(&quot;abc&quot;, &quot;abc&quot;) = true
  1451. * equalsIgnoreCase(&quot;abc&quot;, &quot;ABC&quot;) = true
  1452. * </pre>
  1453. *
  1454. * @param str1 要比较的字符串1
  1455. * @param str2 要比较的字符串2
  1456. * @return 如果两个字符串相同,或者都是<code>null</code>,则返回<code>true</code>
  1457. */
  1458. public static boolean equalsIgnoreCase(CharSequence str1, CharSequence str2)
  1459. {
  1460. return equals(str1, str2, true);
  1461. }
  1462. /**
  1463. * 比较两个字符串是否相等。
  1464. *
  1465. * @param str1 要比较的字符串1
  1466. * @param str2 要比较的字符串2
  1467. * @param ignoreCase 是否忽略大小写
  1468. * @return 如果两个字符串相同,或者都是<code>null</code>,则返回<code>true</code>
  1469. * @since 3.2.0
  1470. */
  1471. public static boolean equals(CharSequence str1, CharSequence str2, boolean ignoreCase)
  1472. {
  1473. if (null == str1)
  1474. {
  1475. // 只有两个都为null才判断相等
  1476. return str2 == null;
  1477. }
  1478. if (null == str2)
  1479. {
  1480. // 字符串2空,字符串1非空,直接false
  1481. return false;
  1482. }
  1483. if (ignoreCase)
  1484. {
  1485. return str1.toString()
  1486. .equalsIgnoreCase(str2.toString());
  1487. }
  1488. else
  1489. {
  1490. return str1.equals(str2);
  1491. }
  1492. }
  1493. /**
  1494. * 创建StringBuilder对象
  1495. *
  1496. * @return StringBuilder对象
  1497. */
  1498. public static StringBuilder builder()
  1499. {
  1500. return new StringBuilder();
  1501. }
  1502. /**
  1503. * 创建StringBuilder对象
  1504. *
  1505. * @param capacity 初始大小
  1506. * @return StringBuilder对象
  1507. */
  1508. public static StringBuilder builder(int capacity)
  1509. {
  1510. return new StringBuilder(capacity);
  1511. }
  1512. /**
  1513. * 创建StringBuilder对象
  1514. *
  1515. * @param strs 初始字符串列表
  1516. * @return StringBuilder对象
  1517. */
  1518. public static StringBuilder builder(CharSequence...strs)
  1519. {
  1520. final StringBuilder sb = new StringBuilder();
  1521. for (CharSequence str: strs)
  1522. {
  1523. sb.append(str);
  1524. }
  1525. return sb;
  1526. }
  1527. /**
  1528. * 创建StringBuilder对象
  1529. *
  1530. * @param sb 初始StringBuilder
  1531. * @param strs 初始字符串列表
  1532. * @return StringBuilder对象
  1533. */
  1534. public static StringBuilder appendBuilder(StringBuilder sb, CharSequence...strs)
  1535. {
  1536. for (CharSequence str: strs)
  1537. {
  1538. sb.append(str);
  1539. }
  1540. return sb;
  1541. }
  1542. /**
  1543. * 获得StringReader
  1544. *
  1545. * @param str 字符串
  1546. * @return StringReader
  1547. */
  1548. public static StringReader getReader(CharSequence str)
  1549. {
  1550. if (null == str)
  1551. {
  1552. return null;
  1553. }
  1554. return new StringReader(str.toString());
  1555. }
  1556. /**
  1557. * 获得StringWriter
  1558. *
  1559. * @return StringWriter
  1560. */
  1561. public static StringWriter getWriter()
  1562. {
  1563. return new StringWriter();
  1564. }
  1565. /**
  1566. * 统计指定内容中包含指定字符的数量
  1567. *
  1568. * @param content 内容
  1569. * @param charForSearch 被统计的字符
  1570. * @return 包含数量
  1571. */
  1572. public static int count(CharSequence content, char charForSearch)
  1573. {
  1574. int count = 0;
  1575. if (isEmpty(content))
  1576. {
  1577. return 0;
  1578. }
  1579. int contentLength = content.length();
  1580. for (int i = 0; i < contentLength; i++)
  1581. {
  1582. if (charForSearch == content.charAt(i))
  1583. {
  1584. count++;
  1585. }
  1586. }
  1587. return count;
  1588. }
  1589. /**
  1590. * 下划线转驼峰
  1591. *
  1592. * @param para 字符串
  1593. * @return String
  1594. */
  1595. public static String underlineToHump(String para)
  1596. {
  1597. StringBuilder result = new StringBuilder();
  1598. String[] a = para.split("_");
  1599. for (String s: a)
  1600. {
  1601. if (result.length() == 0)
  1602. {
  1603. result.append(s.toLowerCase());
  1604. }
  1605. else
  1606. {
  1607. result.append(s.substring(0, 1)
  1608. .toUpperCase());
  1609. result.append(s.substring(1)
  1610. .toLowerCase());
  1611. }
  1612. }
  1613. return result.toString();
  1614. }
  1615. /**
  1616. * 驼峰转下划线
  1617. *
  1618. * @param para 字符串
  1619. * @return String
  1620. */
  1621. public static String humpToUnderline(String para)
  1622. {
  1623. para = firstCharToLower(para);
  1624. StringBuilder sb = new StringBuilder(para);
  1625. int temp = 0;
  1626. for (int i = 0; i < para.length(); i++)
  1627. {
  1628. if (Character.isUpperCase(para.charAt(i)))
  1629. {
  1630. sb.insert(i + temp, "_");
  1631. temp += 1;
  1632. }
  1633. }
  1634. return sb.toString()
  1635. .toLowerCase();
  1636. }
  1637. /**
  1638. * 横线转驼峰
  1639. *
  1640. * @param para 字符串
  1641. * @return String
  1642. */
  1643. public static String lineToHump(String para)
  1644. {
  1645. StringBuilder result = new StringBuilder();
  1646. String[] a = para.split("-");
  1647. for (String s: a)
  1648. {
  1649. if (result.length() == 0)
  1650. {
  1651. result.append(s.toLowerCase());
  1652. }
  1653. else
  1654. {
  1655. result.append(s.substring(0, 1)
  1656. .toUpperCase());
  1657. result.append(s.substring(1)
  1658. .toLowerCase());
  1659. }
  1660. }
  1661. return result.toString();
  1662. }
  1663. /**
  1664. * 驼峰转横线
  1665. *
  1666. * @param para 字符串
  1667. * @return String
  1668. */
  1669. public static String humpToLine(String para)
  1670. {
  1671. para = firstCharToLower(para);
  1672. StringBuilder sb = new StringBuilder(para);
  1673. int temp = 0;
  1674. for (int i = 0; i < para.length(); i++)
  1675. {
  1676. if (Character.isUpperCase(para.charAt(i)))
  1677. {
  1678. sb.insert(i + temp, "-");
  1679. temp += 1;
  1680. }
  1681. }
  1682. return sb.toString()
  1683. .toLowerCase();
  1684. }
  1685. /**
  1686. * trimToEmpty
  1687. *
  1688. * @param str 字符串
  1689. * @return String
  1690. */
  1691. public static String trimToEmpty(String str)
  1692. {
  1693. return str == null ? "" : str.trim();
  1694. }
  1695. /**
  1696. * 替换是否忽略大小写
  1697. *
  1698. * @param text 字符串
  1699. * @param searchString 旧的字符串
  1700. * @param replacement 新的字符串
  1701. * @param ignoreCase true:忽略,false:不忽略
  1702. * @return String
  1703. */
  1704. public static String replaceIgnoreCase(String text, String searchString, String replacement, boolean ignoreCase)
  1705. {
  1706. return replace(text, searchString, replacement, -1, ignoreCase);
  1707. }
  1708. private static String replace(String text, String searchString, String replacement, int max, boolean ignoreCase)
  1709. {
  1710. if (!isEmpty(text) && !isEmpty(searchString) && replacement != null && max != 0)
  1711. {
  1712. if (ignoreCase)
  1713. {
  1714. searchString = searchString.toLowerCase();
  1715. }
  1716. int start = 0;
  1717. int end = indexOf(text, searchString, start, ignoreCase);
  1718. if (end == -1)
  1719. {
  1720. return text;
  1721. }
  1722. else
  1723. {
  1724. int replLength = searchString.length();
  1725. int increase = replacement.length() - replLength;
  1726. increase = increase < 0 ? 0 : increase;
  1727. increase *= max < 0 ? 16 : (max > 64 ? 64 : max);
  1728. StringBuilder buf;
  1729. for (buf = new StringBuilder(text.length() + increase); end != -1; end = indexOf(text, searchString, start, ignoreCase))
  1730. {
  1731. buf.append(text, start, end)
  1732. .append(replacement);
  1733. start = end + replLength;
  1734. --max;
  1735. if (max == 0)
  1736. {
  1737. break;
  1738. }
  1739. }
  1740. buf.append(text, start, text.length());
  1741. return buf.toString();
  1742. }
  1743. }
  1744. else
  1745. {
  1746. return text;
  1747. }
  1748. }
  1749. /**
  1750. * 正则替换字符串
  1751. *
  1752. * @param content 字符串
  1753. * @param pattern 正则表达式
  1754. * @param newString 新的替换字符串
  1755. * @return String
  1756. */
  1757. public static String regReplace(String content, String pattern, String newString)
  1758. {
  1759. Pattern p = Pattern.compile(pattern);
  1760. Matcher m = p.matcher(content);
  1761. String result = m.replaceAll(newString);
  1762. return result;
  1763. }
  1764. }

字符串切分类

  1. import java.util.ArrayList;
  2. import java.util.List;
  3. import java.util.Objects;
  4. import java.util.regex.Matcher;
  5. import java.util.regex.Pattern;
  6. /**
  7. * 字符串切分器
  8. *
  9. * @author Looly
  10. */
  11. public class StrSpliter
  12. {
  13. //---------------------------------------------------------------------------------------------- Split by char
  14. /**
  15. * 切分字符串路径,仅支持Unix分界符:/
  16. *
  17. * @param str 被切分的字符串
  18. * @return 切分后的集合
  19. * @since 3.0.8
  20. */
  21. public static List < String > splitPath(String str)
  22. {
  23. return splitPath(str, 0);
  24. }
  25. /**
  26. * 切分字符串路径,仅支持Unix分界符:/
  27. *
  28. * @param str 被切分的字符串
  29. * @return 切分后的集合
  30. * @since 3.0.8
  31. */
  32. public static String[] splitPathToArray(String str)
  33. {
  34. return toArray(splitPath(str));
  35. }
  36. /**
  37. * 切分字符串路径,仅支持Unix分界符:/
  38. *
  39. * @param str 被切分的字符串
  40. * @param limit 限制分片数
  41. * @return 切分后的集合
  42. * @since 3.0.8
  43. */
  44. public static List < String > splitPath(String str, int limit)
  45. {
  46. return split(str, StringPool.SLASH, limit, true, true);
  47. }
  48. /**
  49. * 切分字符串路径,仅支持Unix分界符:/
  50. *
  51. * @param str 被切分的字符串
  52. * @param limit 限制分片数
  53. * @return 切分后的集合
  54. * @since 3.0.8
  55. */
  56. public static String[] splitPathToArray(String str, int limit)
  57. {
  58. return toArray(splitPath(str, limit));
  59. }
  60. /**
  61. * 切分字符串
  62. *
  63. * @param str 被切分的字符串
  64. * @param separator 分隔符字符
  65. * @param ignoreEmpty 是否忽略空串
  66. * @return 切分后的集合
  67. * @since 3.2.1
  68. */
  69. public static List < String > splitTrim(String str, char separator, boolean ignoreEmpty)
  70. {
  71. return split(str, separator, 0, true, ignoreEmpty);
  72. }
  73. /**
  74. * 切分字符串
  75. *
  76. * @param str 被切分的字符串
  77. * @param separator 分隔符字符
  78. * @param isTrim 是否去除切分字符串后每个元素两边的空格
  79. * @param ignoreEmpty 是否忽略空串
  80. * @return 切分后的集合
  81. * @since 3.0.8
  82. */
  83. public static List < String > split(String str, char separator, boolean isTrim, boolean ignoreEmpty)
  84. {
  85. return split(str, separator, 0, isTrim, ignoreEmpty);
  86. }
  87. /**
  88. * 切分字符串,大小写敏感,去除每个元素两边空白符
  89. *
  90. * @param str 被切分的字符串
  91. * @param separator 分隔符字符
  92. * @param limit 限制分片数,-1不限制
  93. * @param ignoreEmpty 是否忽略空串
  94. * @return 切分后的集合
  95. * @since 3.0.8
  96. */
  97. public static List < String > splitTrim(String str, char separator, int limit, boolean ignoreEmpty)
  98. {
  99. return split(str, separator, limit, true, ignoreEmpty, false);
  100. }
  101. /**
  102. * 切分字符串,大小写敏感
  103. *
  104. * @param str 被切分的字符串
  105. * @param separator 分隔符字符
  106. * @param limit 限制分片数,-1不限制
  107. * @param isTrim 是否去除切分字符串后每个元素两边的空格
  108. * @param ignoreEmpty 是否忽略空串
  109. * @return 切分后的集合
  110. * @since 3.0.8
  111. */
  112. public static List < String > split(String str, char separator, int limit, boolean isTrim, boolean ignoreEmpty)
  113. {
  114. return split(str, separator, limit, isTrim, ignoreEmpty, false);
  115. }
  116. /**
  117. * 切分字符串,忽略大小写
  118. *
  119. * @param str 被切分的字符串
  120. * @param separator 分隔符字符
  121. * @param limit 限制分片数,-1不限制
  122. * @param isTrim 是否去除切分字符串后每个元素两边的空格
  123. * @param ignoreEmpty 是否忽略空串
  124. * @return 切分后的集合
  125. * @since 3.2.1
  126. */
  127. public static List < String > splitIgnoreCase(String str, char separator, int limit, boolean isTrim, boolean ignoreEmpty)
  128. {
  129. return split(str, separator, limit, isTrim, ignoreEmpty, true);
  130. }
  131. /**
  132. * 切分字符串
  133. *
  134. * @param str 被切分的字符串
  135. * @param separator 分隔符字符
  136. * @param limit 限制分片数,-1不限制
  137. * @param isTrim 是否去除切分字符串后每个元素两边的空格
  138. * @param ignoreEmpty 是否忽略空串
  139. * @param ignoreCase 是否忽略大小写
  140. * @return 切分后的集合
  141. * @since 3.2.1
  142. */
  143. public static List < String > split(String str, char separator, int limit, boolean isTrim, boolean ignoreEmpty, boolean ignoreCase)
  144. {
  145. if (StringUtil.isEmpty(str))
  146. {
  147. return new ArrayList < String > (0);
  148. }
  149. if (limit == 1)
  150. {
  151. return addToList(new ArrayList < String > (1), str, isTrim, ignoreEmpty);
  152. }
  153. final ArrayList < String > list = new ArrayList < > (limit > 0 ? limit : 16);
  154. int len = str.length();
  155. int start = 0;
  156. for (int i = 0; i < len; i++)
  157. {
  158. if (Objects.equals(separator, str.charAt(i)))
  159. {
  160. addToList(list, str.substring(start, i), isTrim, ignoreEmpty);
  161. start = i + 1;
  162. //检查是否超出范围(最大允许limit-1个,剩下一个留给末尾字符串)
  163. if (limit > 0 && list.size() > limit - 2)
  164. {
  165. break;
  166. }
  167. }
  168. }
  169. return addToList(list, str.substring(start, len), isTrim, ignoreEmpty);
  170. }
  171. /**
  172. * 切分字符串为字符串数组
  173. *
  174. * @param str 被切分的字符串
  175. * @param separator 分隔符字符
  176. * @param limit 限制分片数
  177. * @param isTrim 是否去除切分字符串后每个元素两边的空格
  178. * @param ignoreEmpty 是否忽略空串
  179. * @return 切分后的集合
  180. * @since 3.0.8
  181. */
  182. public static String[] splitToArray(String str, char separator, int limit, boolean isTrim, boolean ignoreEmpty)
  183. {
  184. return toArray(split(str, separator, limit, isTrim, ignoreEmpty));
  185. }
  186. //---------------------------------------------------------------------------------------------- Split by String
  187. /**
  188. * 切分字符串,不忽略大小写
  189. *
  190. * @param str 被切分的字符串
  191. * @param separator 分隔符字符串
  192. * @param isTrim 是否去除切分字符串后每个元素两边的空格
  193. * @param ignoreEmpty 是否忽略空串
  194. * @return 切分后的集合
  195. * @since 3.0.8
  196. */
  197. public static List < String > split(String str, String separator, boolean isTrim, boolean ignoreEmpty)
  198. {
  199. return split(str, separator, -1, isTrim, ignoreEmpty, false);
  200. }
  201. /**
  202. * 切分字符串,去除每个元素两边空格,忽略大小写
  203. *
  204. * @param str 被切分的字符串
  205. * @param separator 分隔符字符串
  206. * @param ignoreEmpty 是否忽略空串
  207. * @return 切分后的集合
  208. * @since 3.2.1
  209. */
  210. public static List < String > splitTrim(String str, String separator, boolean ignoreEmpty)
  211. {
  212. return split(str, separator, true, ignoreEmpty);
  213. }
  214. /**
  215. * 切分字符串,不忽略大小写
  216. *
  217. * @param str 被切分的字符串
  218. * @param separator 分隔符字符串
  219. * @param limit 限制分片数
  220. * @param isTrim 是否去除切分字符串后每个元素两边的空格
  221. * @param ignoreEmpty 是否忽略空串
  222. * @return 切分后的集合
  223. * @since 3.0.8
  224. */
  225. public static List < String > split(String str, String separator, int limit, boolean isTrim, boolean ignoreEmpty)
  226. {
  227. return split(str, separator, limit, isTrim, ignoreEmpty, false);
  228. }
  229. /**
  230. * 切分字符串,去除每个元素两边空格,忽略大小写
  231. *
  232. * @param str 被切分的字符串
  233. * @param separator 分隔符字符串
  234. * @param limit 限制分片数
  235. * @param ignoreEmpty 是否忽略空串
  236. * @return 切分后的集合
  237. * @since 3.2.1
  238. */
  239. public static List < String > splitTrim(String str, String separator, int limit, boolean ignoreEmpty)
  240. {
  241. return split(str, separator, limit, true, ignoreEmpty);
  242. }
  243. /**
  244. * 切分字符串,忽略大小写
  245. *
  246. * @param str 被切分的字符串
  247. * @param separator 分隔符字符串
  248. * @param limit 限制分片数
  249. * @param isTrim 是否去除切分字符串后每个元素两边的空格
  250. * @param ignoreEmpty 是否忽略空串
  251. * @return 切分后的集合
  252. * @since 3.2.1
  253. */
  254. public static List < String > splitIgnoreCase(String str, String separator, int limit, boolean isTrim, boolean ignoreEmpty)
  255. {
  256. return split(str, separator, limit, isTrim, ignoreEmpty, true);
  257. }
  258. /**
  259. * 切分字符串,去除每个元素两边空格,忽略大小写
  260. *
  261. * @param str 被切分的字符串
  262. * @param separator 分隔符字符串
  263. * @param limit 限制分片数
  264. * @param ignoreEmpty 是否忽略空串
  265. * @return 切分后的集合
  266. * @since 3.2.1
  267. */
  268. public static List < String > splitTrimIgnoreCase(String str, String separator, int limit, boolean ignoreEmpty)
  269. {
  270. return split(str, separator, limit, true, ignoreEmpty, true);
  271. }
  272. /**
  273. * 切分字符串
  274. *
  275. * @param str 被切分的字符串
  276. * @param separator 分隔符字符串
  277. * @param limit 限制分片数
  278. * @param isTrim 是否去除切分字符串后每个元素两边的空格
  279. * @param ignoreEmpty 是否忽略空串
  280. * @param ignoreCase 是否忽略大小写
  281. * @return 切分后的集合
  282. * @since 3.2.1
  283. */
  284. public static List < String > split(String str, String separator, int limit, boolean isTrim, boolean ignoreEmpty, boolean ignoreCase)
  285. {
  286. if (StringUtil.isEmpty(str))
  287. {
  288. return new ArrayList < String > (0);
  289. }
  290. if (limit == 1)
  291. {
  292. return addToList(new ArrayList < String > (1), str, isTrim, ignoreEmpty);
  293. }
  294. if (StringUtil.isEmpty(separator))
  295. {
  296. return split(str, limit);
  297. }
  298. else if (separator.length() == 1)
  299. {
  300. return split(str, separator.charAt(0), limit, isTrim, ignoreEmpty, ignoreCase);
  301. }
  302. final ArrayList < String > list = new ArrayList < > ();
  303. int len = str.length();
  304. int separatorLen = separator.length();
  305. int start = 0;
  306. int i = 0;
  307. while (i < len)
  308. {
  309. i = StringUtil.indexOf(str, separator, start, ignoreCase);
  310. if (i > -1)
  311. {
  312. addToList(list, str.substring(start, i), isTrim, ignoreEmpty);
  313. start = i + separatorLen;
  314. //检查是否超出范围(最大允许limit-1个,剩下一个留给末尾字符串)
  315. if (limit > 0 && list.size() > limit - 2)
  316. {
  317. break;
  318. }
  319. }
  320. else
  321. {
  322. break;
  323. }
  324. }
  325. return addToList(list, str.substring(start, len), isTrim, ignoreEmpty);
  326. }
  327. /**
  328. * 切分字符串为字符串数组
  329. *
  330. * @param str 被切分的字符串
  331. * @param separator 分隔符字符
  332. * @param limit 限制分片数
  333. * @param isTrim 是否去除切分字符串后每个元素两边的空格
  334. * @param ignoreEmpty 是否忽略空串
  335. * @return 切分后的集合
  336. * @since 3.0.8
  337. */
  338. public static String[] splitToArray(String str, String separator, int limit, boolean isTrim, boolean ignoreEmpty)
  339. {
  340. return toArray(split(str, separator, limit, isTrim, ignoreEmpty));
  341. }
  342. //---------------------------------------------------------------------------------------------- Split by Whitespace
  343. /**
  344. * 使用空白符切分字符串<br>
  345. * 切分后的字符串两边不包含空白符,空串或空白符串并不做为元素之一
  346. *
  347. * @param str 被切分的字符串
  348. * @param limit 限制分片数
  349. * @return 切分后的集合
  350. * @since 3.0.8
  351. */
  352. public static List < String > split(String str, int limit)
  353. {
  354. if (StringUtil.isEmpty(str))
  355. {
  356. return new ArrayList < String > (0);
  357. }
  358. if (limit == 1)
  359. {
  360. return addToList(new ArrayList < String > (1), str, true, true);
  361. }
  362. final ArrayList < String > list = new ArrayList < > ();
  363. int len = str.length();
  364. int start = 0;
  365. for (int i = 0; i < len; i++)
  366. {
  367. if (StringUtil.isEmpty(str.charAt(i)))
  368. {
  369. addToList(list, str.substring(start, i), true, true);
  370. start = i + 1;
  371. if (limit > 0 && list.size() > limit - 2)
  372. {
  373. break;
  374. }
  375. }
  376. }
  377. return addToList(list, str.substring(start, len), true, true);
  378. }
  379. /**
  380. * 切分字符串为字符串数组
  381. *
  382. * @param str 被切分的字符串
  383. * @param limit 限制分片数
  384. * @return 切分后的集合
  385. * @since 3.0.8
  386. */
  387. public static String[] splitToArray(String str, int limit)
  388. {
  389. return toArray(split(str, limit));
  390. }
  391. //---------------------------------------------------------------------------------------------- Split by regex
  392. /**
  393. * 通过正则切分字符串
  394. *
  395. * @param str 字符串
  396. * @param separatorPattern 分隔符正则{@link Pattern}
  397. * @param limit 限制分片数
  398. * @param isTrim 是否去除切分字符串后每个元素两边的空格
  399. * @param ignoreEmpty 是否忽略空串
  400. * @return 切分后的集合
  401. * @since 3.0.8
  402. */
  403. public static List < String > split(String str, Pattern separatorPattern, int limit, boolean isTrim, boolean ignoreEmpty)
  404. {
  405. if (StringUtil.isEmpty(str))
  406. {
  407. return new ArrayList < String > (0);
  408. }
  409. if (limit == 1)
  410. {
  411. return addToList(new ArrayList < String > (1), str, isTrim, ignoreEmpty);
  412. }
  413. if (null == separatorPattern)
  414. {
  415. return split(str, limit);
  416. }
  417. final Matcher matcher = separatorPattern.matcher(str);
  418. final ArrayList < String > list = new ArrayList < > ();
  419. int len = str.length();
  420. int start = 0;
  421. while (matcher.find())
  422. {
  423. addToList(list, str.substring(start, matcher.start()), isTrim, ignoreEmpty);
  424. start = matcher.end();
  425. if (limit > 0 && list.size() > limit - 2)
  426. {
  427. break;
  428. }
  429. }
  430. return addToList(list, str.substring(start, len), isTrim, ignoreEmpty);
  431. }
  432. /**
  433. * 通过正则切分字符串为字符串数组
  434. *
  435. * @param str 被切分的字符串
  436. * @param separatorPattern 分隔符正则{@link Pattern}
  437. * @param limit 限制分片数
  438. * @param isTrim 是否去除切分字符串后每个元素两边的空格
  439. * @param ignoreEmpty 是否忽略空串
  440. * @return 切分后的集合
  441. * @since 3.0.8
  442. */
  443. public static String[] splitToArray(String str, Pattern separatorPattern, int limit, boolean isTrim, boolean ignoreEmpty)
  444. {
  445. return toArray(split(str, separatorPattern, limit, isTrim, ignoreEmpty));
  446. }
  447. //---------------------------------------------------------------------------------------------- Split by length
  448. /**
  449. * 根据给定长度,将给定字符串截取为多个部分
  450. *
  451. * @param str 字符串
  452. * @param len 每一个小节的长度
  453. * @return 截取后的字符串数组
  454. */
  455. public static String[] splitByLength(String str, int len)
  456. {
  457. int partCount = str.length() / len;
  458. int lastPartCount = str.length() % len;
  459. int fixPart = 0;
  460. if (lastPartCount != 0)
  461. {
  462. fixPart = 1;
  463. }
  464. final String[] strs = new String[partCount + fixPart];
  465. for (int i = 0; i < partCount + fixPart; i++)
  466. {
  467. if (i == partCount + fixPart - 1 && lastPartCount != 0)
  468. {
  469. strs[i] = str.substring(i * len, i * len + lastPartCount);
  470. }
  471. else
  472. {
  473. strs[i] = str.substring(i * len, i * len + len);
  474. }
  475. }
  476. return strs;
  477. }
  478. //---------------------------------------------------------------------------------------------------------- Private method start
  479. /**
  480. * 将字符串加入List中
  481. *
  482. * @param list 列表
  483. * @param part 被加入的部分
  484. * @param isTrim 是否去除两端空白符
  485. * @param ignoreEmpty 是否略过空字符串(空字符串不做为一个元素)
  486. * @return 列表
  487. */
  488. private static List < String > addToList(List < String > list, String part, boolean isTrim, boolean ignoreEmpty)
  489. {
  490. part = part.toString();
  491. if (isTrim)
  492. {
  493. part = part.trim();
  494. }
  495. if (false == ignoreEmpty || false == part.isEmpty())
  496. {
  497. list.add(part);
  498. }
  499. return list;
  500. }
  501. /**
  502. * List转Array
  503. *
  504. * @param list List
  505. * @return Array
  506. */
  507. private static String[] toArray(List < String > list)
  508. {
  509. return list.toArray(new String[list.size()]);
  510. }
  511. //---------------------------------------------------------------------------------------------------------- Private method end
  512. }

获取Token工具类

  1. import com.alibaba.fastjson.JSON;
  2. import com.alibaba.fastjson.JSONObject;
  3. import lombok.extern.slf4j.Slf4j;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.http.*;
  6. import org.springframework.stereotype.Component;
  7. import org.springframework.web.client.RestTemplate;
  8. import java.util.HashMap;
  9. import java.util.Map;
  10.  
  11. @Slf4j
  12. @Component
  13. public class TokenUtil
  14. {
  15. @Autowired
  16. private RestTemplateUtil restTemplateUtil;
  17. public String getToken(String username, String password, String url)
  18. {
  19. HttpHeaders httpHeaders = new HttpHeaders();
  20. httpHeaders.setContentType(MediaType.APPLICATION_JSON);
  21. //设置参数
  22. JSONObject json = new JSONObject();
  23. json.put("username", username);
  24. json.put("password", password);
  25. HttpEntity < Object > requestEntity = new HttpEntity < > (json, httpHeaders);
  26. RestTemplate restTemplate = new RestTemplate();
  27. ResponseEntity < String > responseEntity = restTemplate.postForEntity(url, requestEntity, String.class);
  28. String result = responseEntity.getBody();
  29. log.info(result);
  30. JSONObject object = JSONObject.parseObject(result);
  31. Integer code = object.getInteger("code");
  32. if (code == HttpStatus.OK.value())
  33. {
  34. return object.getString("token");
  35. }
  36. else
  37. {
  38. log.error("获取token失败");
  39. return "";
  40. }
  41. }
  42. }

有用的工具类(Java)的更多相关文章

  1. JavaSE-基础语法(二)-系统类(java.lang.*)和工具类(java.util.*)

    系统类(java.lang.*)和工具类(java.util.*) 一.系统类(java.lang.*) 这个包下包含java语言的核心类,如String.Math.System和Thread类等,使 ...

  2. 获取Spring容器中Bean实例的工具类(Java泛型方法实现)

    在使用Spring做IoC容器的时候,有的类不方便直接注入bean,需要手动获得一个类型的bean. 因此,实现一个获得bean实例的工具类,就很有必要. 以前,写了一个根据bean的名称和类型获取b ...

  3. 一些非常有用的工具类之javamail(from韩顺平)

    之前编写一个类淘宝服务器时,需要使用javamail发送邮件,搜到的一个工具类,很有用. 需要下载导入:activation.jar和mail.jar package com.cx.service; ...

  4. 加密解密工具类(Java,DES)

    一个Java版的DES加密工具类,能够用来进行网络传输数据加密,保存password的时候进行加密. import java.security.Key; import java.security.sp ...

  5. java工具类——java将一串数据按照gzip方式压缩和解压缩

    我要整理在工作中用到的工具类分享出来,也方便自己以后查阅使用,这些工具类都是我自己实际工作中使用的 import java.io.ByteArrayInputStream; import java.i ...

  6. redis集群使用Java工具类(Java jedis集群工具类)

    package com.xiaomi.weather.vote.webservices.util.redisCache; import com.google.common.base.Strings; ...

  7. Redis 工具类 java 实现的redis 工具类

    最近了解了一下非关系型数据库 redis 会使用简单的命令 在自己本地电脑 使用时必须先启动服务器端 在启动客户端 redis 简介 Redis是一个开源的使用ANSI C语言编写.支持网络.可基于内 ...

  8. Http请求工具类(Java原生Form+Json)

    package com.tzx.cc.common.constant.util; import java.io.IOException; import java.io.InputStream; imp ...

  9. 005-guava 集合-集合工具类-java.util.Collections中未包含的集合工具[Maps,Lists,Sets],Iterables、Multisets、Multimaps、Tables

    一.概述 工具类与特定集合接口的对应关系归纳如下: 集合接口 属于JDK还是Guava 对应的Guava工具类 Collection JDK Collections2:不要和java.util.Col ...

  10. 二维码生成工具类java版

    注意:这里我不提供所需jar包的路径,我会把所有引用的jar包显示出来,大家自行Google package com.net.util; import java.awt.BasicStroke; im ...

随机推荐

  1. 快捷键:mysql + idea + 浏览器

    mysql快捷键:ctrl+r 运行查询窗口的sql语句ctrl+shift+r 只运行选中的sql语句ctrl+q 打开一个新的查询窗口ctrl+w 关闭一个查询窗口ctrl+/ 注释sql语句 c ...

  2. vue学习笔记 十、状态管理基础结构

    系列导航 vue学习笔记 一.环境搭建 vue学习笔记 二.环境搭建+项目创建 vue学习笔记 三.文件和目录结构 vue学习笔记 四.定义组件(组件基本结构) vue学习笔记 五.创建子组件实例 v ...

  3. SpringMVC的特性及应用

    Spring MVC特点 清晰地角色划分 灵活的配置功能 提供了大量的控制器接口和实现类 真正的View层实现无关(JSP.Velocity.Xslt等) 国际化支持 面向接口编程 Spring提供了 ...

  4. WIN32 动态 UAC 提权

    UAC(User Account Control) 是 Windows 平台的用户权限控制.它可以让程序使用管理员权限执行某些操作. 静态 UAC 提权 静态 UAC 提权让程序一直运行在管理员权限下 ...

  5. Vue第四篇 Vue路由系统

    01-路由注册 <!DOCTYPE html> <html lang="en"> <head> <meta charset="U ...

  6. SV 设计特性

    过程语句块特性 ABC 过程块语句 always_comb 防止多驱动的问题:赋值块左侧的语句无法被另一个过程块赋值 if语句没有写else,sv会提示警告,sv认为是latch always不会再仿 ...

  7. 【Gerrit】 快捷操作

    A:添加Reviewers V+B:Pachset刷到最新 D:Download patch J.K:文件移动选中 R:文件Reviewed状态修改 S:五星状态修改,可用于分类管理 U:返回上层 I ...

  8. Linux-软件包管理-rpm-yum-apt

  9. [转帖]细说:Unicode, UTF-8, UTF-16, UTF-32, UCS-2, UCS-4

    https://www.cnblogs.com/malecrab/p/5300503.html 1. Unicode与ISO 10646 全世界很多个国家都在为自己的文字编码,并且互不想通,不同的语言 ...

  10. [转帖]harbor-db restarting问题

    现象: 在安装harbor后,启动时发现harbor-db 一直是restarting,/harbor-jobservice,/harbor-core 这两是starting 状态,如下图 解决: 1 ...