StringUtil.java 19.1 KB
Newer Older
licc's avatar
licc committed
1 2 3 4 5 6 7 8 9 10 11 12
package cn.wisenergy.common.utils;

import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

m1991's avatar
m1991 committed
13 14 15 16 17 18 19 20 21 22
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.util.*;

licc's avatar
licc committed
23 24 25
/**
 * 字符串工具类
 */
m1991's avatar
m1991 committed
26 27 28
@Component("springUtils")
@Lazy(false)
public final class StringUtil implements ApplicationContextAware,
licc's avatar
licc committed
29
        DisposableBean {
m1991's avatar
m1991 committed
30

licc's avatar
licc committed
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566

    /**
     * String转为Integer
     *
     * @param str
     * @return
     */
    public static Integer stringToInteger(String str) {
        if (str != null && !str.equalsIgnoreCase("")) {
            try {
                return new Integer(str);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * String转为Long
     *
     * @param str
     * @return
     */
    public static Long stringToLong(String str) {
        if (str != null && !str.equalsIgnoreCase("")) {
            try {
                return new Long(str);
            } catch (NumberFormatException e) {
            }
        }
        return null;
    }

    /**
     * 将字符串数组转化成Long数组
     *
     * @param strArr
     * @return
     */
    public static Long[] strArrToLongArr(String[] strArr) {
        Long[] longArr = new Long[strArr.length];
        for (int i = 0; i < strArr.length; i++) {
            longArr[i] = stringToLong(strArr[i]);
        }
        return longArr;
    }

    /**
     * 将字符串转化为Boolean类型
     *
     * @param str
     * @return
     */
    public static Double stringToDouble(String str) {
        if (str != null && !str.equalsIgnoreCase("")) {
            try {
                return new Double(str);
            } catch (NumberFormatException e) {
            }
        }
        return null;
    }

    /**
     * 将字符串转化为BigDecimal
     *
     * @param str
     * @return
     */
    public static BigDecimal stringToDecimal(String str) {
        if (StringUtils.isNotEmpty(str)) {
            try {
                return new BigDecimal(str);
            } catch (NumberFormatException e) {
            }
        }
        return null;
    }

    /**
     * 是否为BigDecimal类型
     *
     * @param str
     * @return
     */
    public static boolean isDecimal(String str) {
        boolean res = true;
        if (StringUtils.isEmpty(str)) {
            return false;
        }
        try {
            new BigDecimal(str);
        } catch (NumberFormatException e) {
            res = false;
        }
        return res;
    }

    /**
     * 格式化double为字符串
     *
     * @param num
     * @param pattern
     * @return
     */
    public static String formatNumToString(double num, String pattern) {
        DecimalFormat format = new DecimalFormat(pattern);
        return format.format(num);
    }

    /**
     * 格式化long为字符串
     *
     * @param num
     * @param pattern
     * @return
     */
    public static String formatNumToString(long num, String pattern) {
        DecimalFormat format = new DecimalFormat(pattern);
        return format.format(num);
    }

    /**
     * 格式化BigDecimal为字符串
     *
     * @param num
     * @param pattern
     * @return
     */
    public static String formatNumToString(BigDecimal num, String pattern) {
        DecimalFormat format = new DecimalFormat(pattern);
        return format.format(num.doubleValue());
    }

    /**
     * 格式化BigDiemal为固定格式的字符串
     *
     * @param num
     * @return
     */
    public static String formatNumToString(BigDecimal num) {
        return formatNumToString(num, "#,###.##");
    }

    /**
     * 格式化日期
     *
     * @param date
     * @param pattern
     * @return
     */
    public static Date formatDate(Date date, String pattern) {
        SimpleDateFormat dsf = new SimpleDateFormat(pattern);
        String dateStr = dsf.format(date);
        try {
            return dsf.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    /**
     * 将字符串做重复多次的拼接
     *
     * @param str
     * @param n
     * @return
     */
    public static String dupStr(String str, int n) {
        StringBuffer sb = new StringBuffer("");
        for (int i = 1; i <= n; i++) {
            sb.append(str);
        }
        return sb.toString();
    }

    public static String dateToString(Date date) {
        return dateToString(date, "yyyy-MM-dd");
    }

    public static String datetimeToString(Date date) {
        return dateToString(date, "yyyy-MM-dd HH:mm:ss");
    }

    public static String dateToString(Date date, String pattern) {
        if (date != null) {
            SimpleDateFormat sdf = new SimpleDateFormat(pattern);
            return sdf.format(date);
        } else {
            return null;
        }
    }

    public static Date stringToDate(String str) {
        return stringToDate(str, "yyyy-MM-dd");
    }

    public static Date stringToDatetime(String str) {
        return stringToDate(str, "yyyy-MM-dd HH:mm:ss");
    }

    public static Date stringToDate(String str, String pattern) {
        if (StringUtils.isNotEmpty(str)) {
            SimpleDateFormat sdf = new SimpleDateFormat(pattern);
            try {
                return sdf.parse(str);
            } catch (ParseException e) {
                return null;
            }
        } else {
            return null;
        }
    }

    /**
     * double类型精度的四舍五入
     *
     * @param v
     * @param scale
     * @return
     */
    public static double round(double v, int scale) {
        if (scale < 0) {
            throw new IllegalArgumentException(
                    "The scale must be a positive integer or zero");
        } else {
            BigDecimal b = new BigDecimal(Double.toString(v));
            BigDecimal one = new BigDecimal("1");
            return b.divide(one, scale, 4).doubleValue();
        }
    }

    /**
     * 根据长度截取字符串,超过长度截取,否则不截取
     *
     * @param str
     * @param len
     * @return
     */
    public static String subStrByLen(String str, int len) {
        if (StringUtils.isNotEmpty(str)) {
            return str.trim().length() > len ? str.trim().substring(0, len)
                    : str.trim();
        }
        return str;
    }

    /**
     * 转换数组为字符串,中间用split隔开
     *
     * @param arr
     * @param split
     * @return
     */
    public static String arrayToString(String[] arr, String split) {
        if (arr == null || arr.length == 0)
            return "";

        StringBuffer buffer = new StringBuffer("");

        for (int i = 0; i < arr.length; i++) {

            if (StringUtils.isEmpty(arr[i]))
                continue;

            buffer.append(arr[i]);
            buffer.append(split);
        }

        return buffer.length() > 0 ? buffer.substring(0, buffer.length() - 1)
                : buffer.toString();
    }

    /**
     * 转换字符串数组为字符串,默认用逗号隔开
     *
     * @param arr
     * @return
     */
    public static String arrToString(String arr[]) {
        return arrayToString(arr, ",");
    }

    /**
     * 将\r\n转化为<br/>,主要用于视图页面的显示
     *
     * @param str
     * @return
     */
    public static String converRNToBR(String str) {
        if (StringUtils.isEmpty(str)) {
            return "";
        }
        return str.replaceAll("\r\n", "<br/>");
    }

    /**
     * 判断char类型的字符是否不为表情字符
     *
     * @param codePoint
     * @return
     */
    private static boolean isNotEmojiCharacter(char codePoint) {
        return (codePoint == 0x0) ||
                (codePoint == 0x9) ||
                (codePoint == 0xA) ||
                (codePoint == 0xD) ||
                ((codePoint >= 0x20) && (codePoint <= 0xD7FF)) ||
                ((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) ||
                ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF));
    }

    /**
     * 过滤emoji 或者 其他非文字类型的字符
     *
     * @param source
     * @return
     */
    public static String filterEmoji(String source) {
        if (source == null) {
            return null;
        }
        int len = source.length();
        StringBuilder buf = new StringBuilder(len);
        for (int i = 0; i < len; i++) {
            char codePoint = source.charAt(i);
            if (isNotEmojiCharacter(codePoint)) {
                buf.append(codePoint);
            }
        }
        return buf.toString();
    }

    /**
     * 去除字符串中的双引号
     *
     * @param str
     * @return
     */
    public static String trimDoubleQuotations(String str) {
        if (str == null) {
            return null;
        }
        return str.replaceAll("\"", "");
    }

    /**
     * 判断字符是否为中文
     *
     * @param c
     * @return
     */
    public static boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION) {
            return true;
        }
        return false;
    }

    /**
     * 判断字符串是否包括中文
     *
     * @param strName
     * @return
     */
    public static boolean isContainsChinese(String strName) {
        char[] ch = strName.toCharArray();
        for (int i = 0; i < ch.length; i++) {
            char c = ch[i];
            if (isChinese(c)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取字符串长度(汉子算两位)
     *
     * @param s
     * @return
     */
    public static int getLength(String s) {
        int length = 0;
        char[] ch = s.toCharArray();
        for (char c : ch) {
            if (StringUtil.isChinese(c)) {
                length += 2;
            } else {
                length += 1;
            }
        }
        return length;
    }


    /**
     * 获取字符串长度(汉子算两位)
     *
     * @param s
     * @return
     */
    public static int getLengthByUtf8(String s) {
        int length = 0;
        char[] ch = s.toCharArray();
        for (char c : ch) {
            if (StringUtil.isChinese(c)) {
                length += 3;
            } else {
                length += 1;
            }
        }
        return length;
    }

    /**
     * 指定长度后面补指定字符
     *
     * @param s
     * @param len
     * @param item
     * @return
     */
    public static String addChars(String s, int len, String item) {
        if (StringUtils.isBlank(s)) {
            return "";
        }

        int length = getLength(s);

        if (length >= len) {
            return s;
        } else {
            int count = len - length;
            StringBuilder sb = new StringBuilder(s);
            for (int i = 0; i < count; i++) {
                sb.append(item);
            }
            return sb.toString();
        }

    }

    /**
     * 指定长度后面补空格
     *
     * @param s
     * @param len
     * @return
     */
    public static String addSpace(String s, int len) {
        return addChars(s, len, " ");
    }

    /**
     * 指定字节长度后面补空格
     *
     * @param s
     * @param len
     * @return
     */
    public static String addSpaceByByteLen(String s, int len) {
        if ("".equals(s)) {
            return StringUtils.rightPad(s, len);
        }
        int length = org.apache.commons.codec.binary.StringUtils.getBytesUtf8(s).length;

        int strLength = getLength(s);

        if (len <= length) {
            return s;
        }
        return StringUtils.rightPad(s, len - (length - strLength));
    }

    /**
     * 指定空格前面补空格
     *
     * @param s
     * @param len
     * @return
     */
    public static String addLeftSpace(String s, int len) {
        int length = getLength(s);
        if (length >= len) {
            return s;
        } else {
            int count = len - length;
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < count; i++) {
                sb.append(" ");
            }
            sb.append(s);
            return sb.toString();
        }
    }

    /**
     * 指定长度两头加空格
     *
     * @param s
     * @param len
     * @return
     */
    public static String addBothSpace(String s, int len) {
        int length = getLength(s);

        if (length >= len) {
            return s;
        } else {
            int count = len - length;
            count = count / 2;
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < count; i++) {
                sb.append(" ");
            }
            StringBuilder sb2 = new StringBuilder();
            sb2.append(sb.toString());
            sb2.append(s);
            sb2.append(sb.toString());
            return sb2.toString();
        }
    }

    /**
     * 把 "1,2,3,4,5,6,7"  转化为list
     *
     * @param s 入参
     * @return 结果
     */
licc's avatar
licc committed
567
    public static List<Long> strToLongArray(String s) {
licc's avatar
licc committed
568 569 570 571
        if (StringUtils.isEmpty(s)) {
            return new ArrayList<>();
        }

licc's avatar
licc committed
572
        List<Long> result = new ArrayList<>();
licc's avatar
licc committed
573 574
        String[] str = s.split(",");
        for (String string : str) {
licc's avatar
licc committed
575
            result.add(Long.valueOf(string));
licc's avatar
licc committed
576 577 578
        }
        return result;
    }
m1991's avatar
m1991 committed
579 580 581 582 583 584 585 586 587 588 589 590 591 592

    /**
     * applicationContext
     */
    private static ApplicationContext applicationContext;


//    public static void setApplicationContext(ApplicationContext applicationContext) {
//        StringUtil.applicationContext = applicationContext;
//    }

    /**
     * 不可实例化
     */
licc's avatar
licc committed
593 594
    private StringUtil() {
    }
m1991's avatar
m1991 committed
595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615

//    public void setApplicationContext(ApplicationContext applicationContext) {
//        SpringUtils.applicationContext = applicationContext;
//    }

    public void destroy() throws Exception {
        applicationContext = null;
    }

    /**
     * 获取applicationContext
     *
     * @return applicationContext
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 获取实例
     *
licc's avatar
licc committed
616
     * @param name Bean名称
m1991's avatar
m1991 committed
617 618 619 620 621 622 623 624 625 626 627
     * @return 实例
     */
    @SuppressWarnings("deprecation")
    public static Object getBean(String name) {
        Assert.hasText(name);
        return applicationContext.getBean(name);
    }

    /**
     * 获取实例
     *
licc's avatar
licc committed
628 629
     * @param name Bean名称
     * @param type Bean类型
m1991's avatar
m1991 committed
630 631 632 633 634 635 636 637 638 639 640
     * @return 实例
     */
    @SuppressWarnings("deprecation")
    public static <T> T getBean(String name, Class<T> type) {
        Assert.hasText(name);
        Assert.notNull(type);
        return applicationContext.getBean(name, type);
    }

    /**
     * 根据传入的字符串和切割方式返回一个Long的集合
licc's avatar
licc committed
641
     *
m1991's avatar
m1991 committed
642 643 644 645 646
     * @param s
     * @param cut
     * @return
     */
    public static Set<Long> string2LongSet(String s, String cut) {
licc's avatar
licc committed
647
        if (StringUtils.isBlank(s)) {
m1991's avatar
m1991 committed
648 649
            return null;
        }
licc's avatar
licc committed
650
        if (StringUtils.isBlank(cut)) {
m1991's avatar
m1991 committed
651 652 653 654 655
            cut = Constants.Connnector.COMMA_;
        }
        String s_temp = s.trim();
        String[] arr = s_temp.split(cut);
        Set<Long> list = new HashSet<Long>();
licc's avatar
licc committed
656
        if (arr == null || arr.length <= 0) {
m1991's avatar
m1991 committed
657 658
            return null;
        }
licc's avatar
licc committed
659 660
        for (String l : arr) {
            if (!StringUtils.isBlank(l)) {
m1991's avatar
m1991 committed
661 662 663 664 665 666 667 668 669 670
                try {
                    list.add(Long.parseLong(l));
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                    continue;
                }
            }
        }
        return list;
    }
licc's avatar
licc committed
671

m1991's avatar
m1991 committed
672 673
    /**
     * 根据传入的字符串和切割方式返回一个object的集合
licc's avatar
licc committed
674
     *
m1991's avatar
m1991 committed
675 676 677 678 679 680 681
     * @param s
     * @param cut
     * @return
     * @author:
     * @date:
     */
    public static List<String> string2StringList(String s, String cut) {
licc's avatar
licc committed
682
        if (StringUtils.isBlank(s)) {
m1991's avatar
m1991 committed
683 684
            return null;
        }
licc's avatar
licc committed
685
        if (StringUtils.isBlank(cut)) {
m1991's avatar
m1991 committed
686 687 688 689 690
            cut = Constants.Connnector.COMMA_;
        }
        String s_temp = s.trim();
        String[] arr = s_temp.split(cut);
        List<String> list = new ArrayList<String>();
licc's avatar
licc committed
691
        if (arr == null || arr.length <= 0) {
m1991's avatar
m1991 committed
692 693
            return null;
        }
licc's avatar
licc committed
694 695
        for (String l : arr) {
            if (!StringUtils.isBlank(l)) {
m1991's avatar
m1991 committed
696 697 698 699 700
                list.add(l);
            }
        }
        return list;
    }
licc's avatar
licc committed
701

m1991's avatar
m1991 committed
702 703
    /**
     * 根据出入的参数创建一个key
licc's avatar
licc committed
704
     *
m1991's avatar
m1991 committed
705 706
     * @return 如果参数为空,那么返回null
     */
licc's avatar
licc committed
707 708
    public static String formatKeys(String... args) {
        if (args != null && args.length > 0) {
m1991's avatar
m1991 committed
709
            StringBuilder key = new StringBuilder();
licc's avatar
licc committed
710
            for (String s : args) {
m1991's avatar
m1991 committed
711 712 713 714 715 716 717 718 719
                key.append(s).append(Constants.Connnector.UNDERLINE);
            }
            return key.toString();
        }
        return null;
    }

    /**
     * 根据出入的参数创建一个Redis key,自动拼接前缀
licc's avatar
licc committed
720
     *
m1991's avatar
m1991 committed
721 722
     * @return 如果参数为空,那么返回null
     */
licc's avatar
licc committed
723 724 725 726
    public static String formatKeyWithPrefix(String... args) {
        if (args != null && args.length > 0) {
            StringBuffer key = new StringBuffer("");
            for (String s : args) {
m1991's avatar
m1991 committed
727 728 729 730 731 732 733 734 735 736
                key.append(s).append(Constants.Connnector.COLON);
            }
            return key.toString();
        }
        return null;
    }


    /**
     * Description: 创建一个简单的map对象
licc's avatar
licc committed
737
     *
m1991's avatar
m1991 committed
738 739 740 741 742 743
     * @param key
     * @param value
     * @return
     * @Author
     * @since
     */
licc's avatar
licc committed
744 745 746 747
    public static Map<String, Object> createSimpleMap(String key, Object value) {
        Map<String, Object> conditions = null;
        if (key != null && !key.equals("")) {
            conditions = new HashMap<String, Object>();
m1991's avatar
m1991 committed
748 749 750 751
            conditions.put(key, value);
        }
        return conditions;
    }
licc's avatar
licc committed
752

m1991's avatar
m1991 committed
753 754 755 756 757
    /***
     * 判断字符串是否为空
     * @param temp
     * @return
     */
licc's avatar
licc committed
758
    public static boolean isBlank(String temp) {
m1991's avatar
m1991 committed
759 760 761 762 763
        return StringUtils.isBlank(temp);
    }

    /**
     * 返回一个没有中划线的32位字符串
licc's avatar
licc committed
764
     *
m1991's avatar
m1991 committed
765 766
     * @return
     */
licc's avatar
licc committed
767 768
    public static String createToken() {
        return UUID.randomUUID().toString().replace("-", "");
m1991's avatar
m1991 committed
769 770 771 772 773 774 775
    }


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        StringUtil.applicationContext = applicationContext;
    }
licc's avatar
licc committed
776
}