Commons-lang3 常用工具类
工具类 | 描述 |
---|---|
ObjectUtils | 对象工具类 |
math.NumberUtils | 数值工具类 |
ArrayUtils | 数组工具类 |
BooleanUtils | 布尔工具类 |
RandomStringUtils | 随机字符串工具类 |
RandomUtils | 随机数值工具类 |
SystemUtils | 系统工具类 |
DateFormatUtils | 日期格式化工具类,将日期转为指定格式的字符串 |
DateUtils | 日期工具类,将指定格式的字符串转为日期 |
Maven依赖
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
StringUtils
-
public static boolean isBlank(String str)
校验一个String类型的变量是否为空 -
public static boolean isNotBlank(String str)
判断某字符串是否不为空且长度不为0且不由空白符(whitespace) 构成 -
public static boolean isEmpty(String str)
判断某字符串是否为空 -
public static boolean isNotEmpty(String str)
判断某字符串是否非空 -
public static String trim(String str)
去掉字符串两端的控制符(control characters, char <= 32) , 如果变为 null,则返回null -
public static String trimToNull(String str)
去掉字符串两端的控制符(control characters, char <= 32) ,如果变为 null 或"",则返回 null -
public static String trimToEmpty(String str)
去掉字符串两端的控制符(control characters, char <= 32) ,如果变为 null 或 “” ,则返回 “” -
public static String strip(String str)
去掉字符串两端的空白符(whitespace) ,如果变入为 null,则返回 null -
public static String stripToNull(String str)
去掉字符串两端的空白符(whitespace) ,如果变为 null 或"",则返回 null -
public static String stripToEmpty(String str)
去掉字符串两端的空白符(whitespace) ,如果变为 null 或"" ,则返回"" -
public static String strip(String str, String stripChars)
去掉 str 两端的在 stripChars 中的字符。
如果 str 为 null 或等于"" ,则返回它本身;
如果 stripChars 为 null 或"" ,则返回 strip(String str) 。 -
public static String stripStart(String str, String stripChars)
去掉 str 前端的在 stripChars 中的字符。 -
public static String stripEnd(String str, String stripChars)
去掉 str 末端的在 stripChars 中的字符。 -
public static String[] stripAll(String[] strs)
对字符串数组中的每个字符串进行 strip(String str) ,然后返回。
如果 strs 为 null 或 strs 长度为0,则返回 strs 本身 -
public static String[] stripAll(String[] strs, String stripChars)
对字符串数组中的每个字符串进行 strip(String str, String stripChars) ,然后返回。
如果 strs 为 null 或 strs 长度为0,则返回 strs 本身 -
public static boolean equals(String str1, String str2)
比较两个字符串是否相等,如果两个均为空则也认为相等。 -
public static boolean equalsIgnoreCase(String str1, String str2)
比较两个字符串是否相等,不区分大小写,如果两个均为空则也认为相等。 -
public static int indexOf(String str, char searchChar)
返回字符 searchChar 在字符串 str 中第一次出现的位置。
如果 searchChar 没有在 str 中出现则返回-1,
如果 str 为 null 或 “” ,则也返回-1 -
public static int indexOf(String str, char searchChar, int startPos)
返回字符 searchChar 从 startPos 开始在字符串 str 中第一次出现的位置。
如果从 startPos 开始 searchChar 没有在 str 中出现则返回-1,
如果 str 为 null 或 “” ,则也返回-1 -
public static int indexOf(String str, String searchStr)
返回字符串 searchStr 在字符串 str 中第一次出现的位置。
如果 str 为 null 或 searchStr 为 null 则返回-1,
如果 searchStr 为 “” ,且 str 为不为 null ,则返回0,
如果 searchStr 不在 str 中,则返回-1 -
public static int ordinalIndexOf(String str, String searchStr, int ordinal)
返回字符串 searchStr 在字符串 str 中第 ordinal 次出现的位置。
如果 str=null 或 searchStr=null 或 ordinal<=0 则返回-1 -
public static int indexOf(String str, String searchStr, int startPos)
返回字符串 searchStr 从 startPos 开始在字符串 str 中第一次出现的位置。 -
public static int lastIndexOf(String str, char searchChar)
返回字符 searchChar 在字符串 str 中最后一次出现的位置。
如果 searchChar 没有在 str 中出现则返回-1,
如果 str 为 null 或 “” ,则也返回-1 -
public static int lastIndexOf(String str, char searchChar, int startPos)
返回字符 searchChar 从 startPos 开始在字符串 str 中最后一次出现的位置。
如果从 startPos 开始 searchChar 没有在 str 中出现则返回-1,
如果 str 为 null 或 “” ,则也返回-1 -
public static int lastIndexOf(String str, String searchStr)
返回字符串 searchStr 在字符串 str 中最后一次出现的位置。
如果 str 为 null 或 searchStr 为 null 则返回-1,
如果 searchStr 为 “” ,且 str 为不为 null ,则返回0,
如果 searchStr 不在 str 中,则返回-1 -
public static int lastIndexOf(String str, String searchStr, int startPos)
返回字符串 searchStr 从 startPos 开始在字符串 str 中最后一次出现的位置。
注意:String 的 split(String regex) 和replaceAll(String a,String b)这两个方法有匹配正则表达式的,所以使用的时用"."是使用转义字符。不让”.“代表全部,结果会出错的哦
示例:
//缩短到某长度,用...结尾.其实就是(substring(str, 0, max-3) + "...")
//public static String abbreviate(String str,int maxWidth)
StringUtils.abbreviate("abcdefg", 6);// ---"abc..."
//字符串结尾的后缀是否与你要结尾的后缀匹配,若不匹配则添加后缀
StringUtils.appendIfMissing("abc","xyz");//---"abcxyz"
StringUtils.appendIfMissingIgnoreCase("abcXYZ","xyz");//---"abcXYZ"
//首字母大小写转换
StringUtils.capitalize("cat");//---"Cat"
StringUtils.uncapitalize("Cat");//---"cat"
//字符串扩充至指定大小且居中(若扩充大小少于原字符大小则返回原字符,若扩充大小为 负数则为0计算 )
StringUtils.center("abcd", 2);//--- "abcd"
StringUtils.center("ab", -1);//--- "ab"
StringUtils.center("ab", 4);//---" ab "
StringUtils.center("a", 4, "yz");//---"yayz"
StringUtils.center("abc", 7, "");//---" abc "
//去除字符串中的"\n", "\r", or "\r\n"
StringUtils.chomp("abc\r\n");//---"abc"
//判断一字符串是否包含另一字符串
StringUtils.contains("abc", "z");//---false
StringUtils.containsIgnoreCase("abc", "A");//---true
//统计一字符串在另一字符串中出现次数
StringUtils.countMatches("abba", "a");//---2
//删除字符串中的梭有空格
StringUtils.deleteWhitespace(" ab c ");//---"abc"
//比较两字符串,返回不同之处。确切的说是返回第二个参数中与第一个参数所不同的字符串
StringUtils.difference("abcde", "abxyz");//---"xyz"
//检查字符串结尾后缀是否匹配
StringUtils.endsWith("abcdef", "def");//---true
StringUtils.endsWithIgnoreCase("ABCDEF", "def");//---true
StringUtils.endsWithAny("abcxyz", new String[] {null, "xyz", "abc"});//---true
//检查起始字符串是否匹配
StringUtils.startsWith("abcdef", "abc");//---true
StringUtils.startsWithIgnoreCase("ABCDEF", "abc");//---true
StringUtils.startsWithAny("abcxyz", new String[] {null, "xyz", "abc"});//---true
//判断两字符串是否相同
StringUtils.equals("abc", "abc");//---true
StringUtils.equalsIgnoreCase("abc", "ABC");//---true
//比较字符串数组内的所有元素的字符序列,起始一致则返回一致的字符串,若无则返回""
StringUtils.getCommonPrefix(new String[] {"abcde", "abxyz"});//---"ab"
//正向查找字符在字符串中第一次出现的位置
StringUtils.indexOf("aabaabaa", "b");//---2
StringUtils.indexOf("aabaabaa", "b", 3);//---5(从角标3后查找)
StringUtils.ordinalIndexOf("aabaabaa", "a", 3);//---1(查找第n次出现的位置)
//反向查找字符串第一次出现的位置
StringUtils.lastIndexOf("aabaabaa", ‘b‘);//---5
StringUtils.lastIndexOf("aabaabaa", ‘b‘, 4);//---2
StringUtils.lastOrdinalIndexOf("aabaabaa", "ab", 2);//---1
//判断字符串大写、小写
StringUtils.isAllUpperCase("ABC");//---true
StringUtils.isAllLowerCase("abC");//---false
//判断是否为空(注:isBlank与isEmpty 区别)
StringUtils.isBlank(null);StringUtils.isBlank("");StringUtils.isBlank(" ");//---true
StringUtils.isNoneBlank(" ", "bar");//---false
StringUtils.isEmpty(null);StringUtils.isEmpty("");//---true
StringUtils.isEmpty(" ");//---false
StringUtils.isNoneEmpty(" ", "bar");//---true
//判断字符串数字
StringUtils.isNumeric("123");//---false
StringUtils.isNumeric("12 3");//---false (不识别运算符号、小数点、空格……)
StringUtils.isNumericSpace("12 3");//---true
//数组中加入分隔符号
//StringUtils.join([1, 2, 3], ‘;‘);//---"1;2;3"
//大小写转换
StringUtils.upperCase("aBc");//---"ABC"
StringUtils.lowerCase("aBc");//---"abc"
StringUtils.swapCase("The dog has a BONE");//---"tHE DOG HAS A bone"
//替换字符串内容……(replacePattern、replceOnce)
StringUtils.replace("aba", "a", "z");//---"zbz"
StringUtils.overlay("abcdef", "zz", 2, 4);//---"abzzef"(指定区域)
StringUtils.replaceEach("abcde", new String[]{"ab", "d"},
new String[]{"w", "t"});//---"wcte"(多组指定替换ab->w,d->t)
//重复字符
StringUtils.repeat(‘e‘, 3);//---"eee"
//反转字符串
StringUtils.reverse("bat");//---"tab"
//删除某字符
StringUtils.remove("queued", ‘u‘);//---"qeed"
//分割字符串
StringUtils.split("a..b.c", ‘.‘);//---["a", "b", "c"]
StringUtils.split("ab:cd:ef", ":", 2);//---["ab", "cd:ef"]
StringUtils.splitByWholeSeparator("ab-!-cd-!-ef", "-!-", 2);//---["ab", "cd-!-ef"]
StringUtils.splitByWholeSeparatorPreserveAllTokens("ab::cd:ef", ":");//-["ab"," ","cd","ef"]
//去除首尾空格,类似trim……(stripStart、stripEnd、stripAll、stripAccents)
StringUtils.strip(" ab c ");//---"ab c"
StringUtils.stripToNull(null);//---null
StringUtils.stripToEmpty(null);//---""
//截取字符串
StringUtils.substring("abcd", 2);//---"cd"
StringUtils.substring("abcdef", 2, 4);//---"cd"
//left、right从左(右)开始截取n位字符
StringUtils.left("abc", 2);//---"ab"
StringUtils.right("abc", 2);//---"bc"
//从第n位开始截取m位字符 n m
StringUtils.mid("abcdefg", 2, 4);//---"cdef"
StringUtils.substringBefore("abcba", "b");//---"a"
StringUtils.substringBeforeLast("abcba", "b");//---"abc"
StringUtils.substringAfter("abcba", "b");//---"cba"
StringUtils.substringAfterLast("abcba", "b");//---"a"
StringUtils.substringBetween("tagabctag", "tag");//---"abc"
StringUtils.substringBetween("yabczyabcz", "y", "z");//---"abc"
ArrayUtils
contains()
isEmpty()
isNotEmpty()
add()
clone()
addAll()
subarray()
indexOf()
EMPTY_OBJECT_ARRAY
EMPTY_STRING_ARRAY
示例:
//创建数组
String[] array = ArrayUtils.toArray("1", "2");
//判断两个数据是否相等,如果内容相同, 顺序相同 则返回 true
ArrayUtils.isEquals(arr1,arr2);
//判断数组中是否包含某一对象
ArrayUtils.contains(arr, "33");
//二维数组转换成MAP
Map map = ArrayUtils.toMap(new String[][] {
{ "RED", "#FF0000" }, { "GREEN", "#00FF00" }, { "BLUE", "#0000FF" } });
RandomUtils
- static int nextInt()
生成 [0, Integer.MAX_VALUE) 之间的随机 int 值 - static int nextInt(final int startInclusive, final int endExclusive)
生成 [startInclusive,endExclusive) 之间的随机整数,起始值不能小于终止值。 - static boolean nextBoolean()
随机生成一个布尔值,true 或者 false - static long nextLong()
生成 [0, Long.MAX_VALUE) 之间的 long 值 - long nextLong(final long startInclusive, final long endExclusive)
生成 [startInclusive,endExclusive) 之间的随机 long 值 - static byte[] nextBytes(final int count)
生成指定个数的字节数组,如 nextBytes(10) 生成的字节数组有 10 个 byte 元素 - static double nextDouble()
生成 [0, Double.MAX_VALUE) 直接的随机 double 值 - double nextDouble(final double startInclusive, final double endInclusive)
生成 [startInclusive,endExclusive) 之间的随机 double 值 - static float nextFloat()
生成 [0, Float.MAX_VALUE) 之间的随机 fluat 值 - float nextFloat(final float startInclusive, final float endInclusive)
生成 [startInclusive,endExclusive) 之间的随机 float 值
RandomStringUtils
- random(final int count)
创建长度为指定个数(count)的随机字符串,将从所有字符集中选择字符,不含字母和数字,如 “篊???椗???垅” - random(final int count, final boolean letters, final boolean numbers)
生成指定个数(count)的随机字符串,字符将从参数指示的字母或数字字符集中选择.
1、letters: 字母字符集、numbers:数字字符集
2、letters 为 true、numbers 为 true:则随机字符串由字母和数字组成
3、letters 为 true、numbers 为 false:则随机字符串由字母组成
4、letters 为 false、numbers 为 true:则随机字符串由数字组成,如 7253440222803746
5、letters 为 false、numbers 为 false:则等同于 random(final int count) - random(final int count, final char… chars)
创建长度为指定个数的随机字符串,从指定的字符集(chars)中选择字符. chars 的个数可以小于 count - random(final int count, final String chars)
从指定的字符集中选择字符生成指定个数的随机字符串 - randomAlphabetic(final int count)
创建指定长度的随机字符串,字符将从 (a-z, A-Z) 中选择,等同于 random(count, true, false) - randomAlphabetic(final int minLengthInclusive, final int maxLengthExclusive)
创建长度介于 [minLengthInclusive,maxLengthExclusive) 之间的随机字符串 - randomAlphanumeric(final int count)
创建长度为指定字符数的随机字符串,从拉丁字母字符集(a-z, A-Z)和数字0-9中选择,等同于 random(count, true, true) - randomAlphanumeric(final int minLengthInclusive, final int maxLengthExclusive)
创建长度介于 [minLengthInclusive,maxLengthExclusive) 之间的随机字符串 - randomAscii(final int count)
随机字符将从 ASCII 码值介于 [32,126] 之间的字符集中选择,等价于:random(count, 32, 127, false, false) - randomAscii(final int minLengthInclusive, final int maxLengthExclusive)
创建的随机字符串个数介于 [minLengthInclusive,maxLengthExclusive) - randomGraph(final int count)
随机字符从所有可见的 ASCII 字符中选择,即除空格和控制字符外的任何内容,等价于:random(count, 33, 126, false, false) - randomGraph(final int minLengthInclusive, final int maxLengthExclusive)
- randomNumeric(final int count):
创建长度为指定字符数的随机字符串,随机字符将从数字字符集中选择。 - randomNumeric(final int minLengthInclusive, final int maxLengthExclusive)
- randomPrint(final int count):
随机字符从所有可见的 ASCII 码字符和空格(即除控制字符外的任何内容)中选择。等价于 random(count, 32, 126, false, false)
示例:
public static void main(String[] args) {
//从所有字符集中选择字符,产生5位长度的随机字符串,中文环境下是乱码
String random1 = RandomStringUtils.random(5);
System.out.println(random1);
/**
* count 长度
* letters 生成的字符串是否包括字母字符
* numbers 生成的字符串是否包含数字字符
*/
String random11 = RandomStringUtils.random(15, true, false);
System.out.println(random11);
//使用指定的字符生成5位长度的随机字符串,第二个参数如果NULL,则使用所有字符集
String random2 = RandomStringUtils.random(5, new char[]{'a', 'b', 'c', 'd', 'e', 'f', '1', '2', '3'});
System.out.println(random2);
//生成指定长度的字母和数字组成的随机组合字符串
String random3 = RandomStringUtils.randomAlphanumeric(5);
System.out.println(random3);
/**
* 创建一个随机字符串,其长度介于包含最小值和最大最大值之间,字符将从拉丁字母(a-z、A-Z)和数字0-9中选择。
* minLengthInclusive :要生成的字符串的包含最小长度
* maxLengthExclusive :要生成的字符串的包含最大长度
*
*/
String random31 = RandomStringUtils.randomAlphanumeric(5, 68);
System.out.println(random31);
//生成随机数字字符串
String random4 = RandomStringUtils.randomNumeric(5);
System.out.println(random4);
/**
* 创建一个随机字符串,其长度介于包含最小值和最大最大值之间,将从数字字符集中选择字符.
* minLengthInclusive, 要生成的字符串的包含最小长度
* maxLengthExclusive 要生成的字符串的包含最大长度
*/
String random41 = RandomStringUtils.randomNumeric(15, 20);
System.out.println(random41);
//生成随机[a-z,A-Z]字符串,包含大小写
String random5 = RandomStringUtils.randomAlphabetic(5);
System.out.println(random5);
/**
* 创建一个随机字符串,其长度介于包含最小值和最大最大值之间,,字符将从拉丁字母(a-z、A-Z的选择)。
* minLengthInclusive :要生成的字符串的最小长度
* maxLengthExclusive :要生成的字符串的最大长度
*/
String random51 = RandomStringUtils.randomAlphabetic(2, 15);
System.out.println(random51);
//生成ASCII值从32到126组成的随机字符串
String random6 = RandomStringUtils.randomAscii(4);
System.out.println(random6);
/**
* 创建一个随机字符串,其长度介于包含最小值和最大最大值之间,字符将从ASCII值介于32到126之间的字符集中选择(包括)
* minLengthInclusive :要生成的字符串的包含最小长度
* maxLengthExclusive :要生成的字符串的包含最大长度
*/
String random61 = RandomStringUtils.randomAscii(15, 30);
System.out.println(random61);
}
某次运行结果:
ObjectUtils
- allNotNull(final Object… values)
检查给定数组中的任何元素值是否都不是 null。 - anyNotNull(final Object… values)
检查给定数组中的元素是否有不是 null 的值。 - clone(final T obj)
克隆对象。如果 obj 为 null,则返回 null. - cloneIfPossible(final T obj)
先调 clone(final T obj) ,如果返回 null,则返回原来的 obj 对象. - compare(final T c1, final T c2)
- compare(final T c1, final T c2, final boolean nullGreater)
1、如果 c1 < c2,则返回负数;如果 c1 > c2,则返回正数;如果 c1 = c2,则返回 0;
2、c1、c2 可以为 null。nullGreater 为 false 时,先判断 c1 如果 null ,则返回 -1,再判断 c2 如果为 null,则返回 1.
3、compare(final T c1, final T c2) 底层是 compare(c1, c2, false) - T defaultIfNull(final T object, final T defaultValue)
如果传递的对象是 null,则返回默认值 - firstNonNull(final T… values)
返回数组中不是 null 的第一个值 - isEmpty(final Object object)
检查对象是否为空,支持:CharSequence、Array、Collection、Map
NumberUtils
示例:
//从数组中选出最大值
NumberUtils.max(new int[] { 1, 2, 3, 4 });//---4
//判断字符串是否全是整数
NumberUtils.isDigits("153.4");//--false
//判断字符串是否是有效数字
NumberUtils.isNumber("0321.1");//---false
DateUtils
示例:
//日期加n天
DateUtils.addDays(new Date(), n);
//判断是否同一天
DateUtils.isSameDay(date1, date2);
//字符串时间转换为Date
DateUtils.parseDate(str, parsePatterns);
DigestUtils
// MD5加密
String encodeStr=DigestUtils.md5Hex(text + key);
// 密钥进行验证
String md5Text = md5(text, key);
if(md5Text.equalsIgnoreCase(md5))
{
System.out.println(“MD5验证通过”);
return true;
}