在此之前对commons包了解的不多,最常用的就是StringUtils.isBlack(str)来取代if(str !=null && str.lenght()>1)的判断,昨天忽然想看看StringUtils是个什么神奇的东西,这一看才发现里面没那么简单!
先看StringUtils中的所有方法:太多了不能一一列出
大概看出来一些规律了吧,都是各种对String操作的静态方法:查找、删除、大小写转换、判断包含……太多了,总之你能想到的和你想不到的它都实现了,这才发现这是个工具类。
到此为止?还没,一个commons-lang.jar总不能只有一个StringUtils类吧?再看看包结构:
看出来什么意思了吧,这整个jar包中都是各种操作工具类,什么日期、数学、随机数、文本操作工具都有!这简直是个神器啊,以后不用再重复造轮子了!
随便举几个例子看看:
@Test public void test07(){ System.out.println(RandomStringUtils.randomAlphabetic(14)); System.out.println(RandomStringUtils.randomAscii(14)); System.out.println(RandomStringUtils.randomAlphabetic(14)); System.out.println(NumberUtils.createInteger("45")); System.out.println(CharEncoding.isSupported("UTF-8")); System.out.println(DateFormatUtils.format(new Date(), "yyyy")); }
运行结果如下:
ZkgPhRzhLSprOx
9MtDmO?horL3C}
jloAZcKrNFkrcm
45
true
2016
本以为这就没了,然后去网上一查才发现commons没这么简单。去这里看看一个神奇的网站
太多了,好多都没用过,即使用过也不知道,唯一熟悉的就FileUpload、Logging、 Lang
有兴趣的自己看吧,链接放这里了。源码官网都能下载的,可以看看。这里有一篇介绍各种工具包的博客可以看看Apache commons (Java常用工具包)简介
把StringUtils的源码看了一些,贴出来看看,其实StringUtils中方法命名很规范的,可以达到见名知意的,这是中每个方法都有示例的,即使不会英文也能理解意思的。
public class StringUtils { // Performance testing notes (JDK 1.4, Jul03, scolebourne) // Whitespace: // Character.isWhitespace() is faster than WHITESPACE.indexOf() // where WHITESPACE is a string of all whitespace characters // // Character access: // String.charAt(n) versus toCharArray(), then array[n] // String.charAt(n) is about 15% worse for a 10K string // They are about equal for a length 50 string // String.charAt(n) is about 4 times better for a length 3 string // String.charAt(n) is best bet overall // // Append: // String.concat about twice as fast as StringBuffer.append // (not sure who tested this) /** * The empty String <code>""</code>. * @since 2.0 */ public static final String EMPTY = ""; /** * Represents a failed index search. * @since 2.1 */ public static final int INDEX_NOT_FOUND = -1; /** * <p>The maximum size to which the padding constant(s) can expand.</p> */ private static final int PAD_LIMIT = 8192; /** * <p><code>StringUtils</code> instances should NOT be constructed in * standard programming. Instead, the class should be used as * <code>StringUtils.trim(" foo ");</code>.</p> * * <p>This constructor is public to permit tools that require a JavaBean * instance to operate.</p> */ public StringUtils() { super(); } /** * <p>Checks if a String is empty ("") or null.</p> *检查String是否为“”或者null,不在使用trim对String进行处理。 * <pre> * StringUtils.isEmpty(null) = true * StringUtils.isEmpty("") = true * StringUtils.isEmpty(" ") = false * StringUtils.isEmpty("bob") = false * StringUtils.isEmpty(" bob ") = false * </pre> * @param str the String to check, may be null * @return <code>true</code> if the String is empty or null */ public static boolean isEmpty(String str) { return str == null || str.length() == 0; } /** * <p>Checks if a String is not empty ("") and not null.</p> *检查str是否不为“”或者null,看看实现方式就明白了。 * <pre> * StringUtils.isNotEmpty(null) = false * StringUtils.isNotEmpty("") = false * StringUtils.isNotEmpty(" ") = true * StringUtils.isNotEmpty("bob") = true * StringUtils.isNotEmpty(" bob ") = true * </pre> * * @param str the String to check, may be null * @return <code>true</code> if the String is not empty and not null */ public static boolean isNotEmpty(String str) { return !StringUtils.isEmpty(str); } /** * <p>Checks if a String is whitespace, empty ("") or null.</p> *检查str是否为空白字符串“ ”、“”、或者null。 * <pre> * StringUtils.isBlank(null) = true * StringUtils.isBlank("") = true * StringUtils.isBlank(" ") = true * StringUtils.isBlank("bob") = false * StringUtils.isBlank(" bob ") = false * </pre> */ public static boolean isBlank(String str) { int strLen; //为null或者长度为0则返回false if (str == null || (strLen = str.length()) == 0) { return true; } //长度大于0时逐个检查字符是否为空格 for (int i = 0; i < strLen; i++) { if ((Character.isWhitespace(str.charAt(i)) == false)) { return false; } } return true; } /** * <p>Checks if a String is not empty (""), not null and not whitespace only.</p> *检查str是否不为空白字符串“ ”、“”、或者null。 * <pre> * StringUtils.isNotBlank(null) = false * StringUtils.isNotBlank("") = false * StringUtils.isNotBlank(" ") = false * StringUtils.isNotBlank("bob") = true * StringUtils.isNotBlank(" bob ") = true * </pre> */ public static boolean isNotBlank(String str) { return !StringUtils.isBlank(str); } // Trim //----------------------------------------------------------------------- /** * <p>Removes control characters (char <= 32) from both * ends of this String, handling <code>null</code> by returning * an empty String ("").</p> *如同,str.trim(),从str的两端去除控制字符。 *这里需要明白什么是控制字符:空格 \t …… *实际上是调用String的trim来实现的,只是添加了一个null情况的处理 * <pre> * StringUtils.clean(null) = "" * StringUtils.clean("") = "" * StringUtils.clean("abc") = "abc" * StringUtils.clean(" abc ") = "abc" * StringUtils.clean(" ") = "" * StringUtils.clean("\t f d ") = "f d" * </pre> * */ public static String clean(String str) { return str == null ? EMPTY : str.trim(); } //String中的trim方法 public String trim() { int len = count; int st = 0; int off = offset; char[] val = value; //从前到后找到第一个不为' '的字符位置 //注意这里val[off + st] <= ' ',这里比较的是charCode,所有比' '的charCode 32小的值都被过滤掉。 while ((st < len) && (val[off + st] <= ' ')) { st++; } //从后向前找到最后一个不为' '的字符位置 while ((st < len) && (val[off + len - 1] <= ' ')) { len--; } //对str进行截取 return ((st > 0) || (len < count)) ? substring(st, len) : this; } /** *和上面的区别就是当str为null的时候返回的是null,而clean返回的是"" * <pre> * StringUtils.trim(null) = null * StringUtils.trim("") = "" * StringUtils.trim(" ") = "" * StringUtils.trim("abc") = "abc" * StringUtils.trim(" abc ") = "abc" * </pre> */ public static String trim(String str) { return str == null ? null : str.trim(); } /** * <p>Removes control characters (char <= 32) from both * ends of this String returning <code>null</code> if the String is * empty ("") after the trim or if it is <code>null</code>. *把str经过trim之后判断,返回null或者非空字符串,不会返回"". * * <pre> * StringUtils.trimToNull(null) = null * StringUtils.trimToNull("") = null * StringUtils.trimToNull(" ") = null * StringUtils.trimToNull("abc") = "abc" * StringUtils.trimToNull(" abc ") = "abc" * </pre> */ public static String trimToNull(String str) { String ts = trim(str); return isEmpty(ts) ? null : ts; } /** * <p>Removes control characters (char <= 32) from both * ends of this String returning an empty String ("") if the String * is empty ("") after the trim or if it is <code>null</code>. * *和trimToNull正好相反,返回的为""或者字符串,不会返回null。 * <pre> * StringUtils.trimToEmpty(null) = "" * StringUtils.trimToEmpty("") = "" * StringUtils.trimToEmpty(" ") = "" * StringUtils.trimToEmpty("abc") = "abc" * StringUtils.trimToEmpty(" abc ") = "abc" * </pre> * */ public static String trimToEmpty(String str) { return str == null ? EMPTY : str.trim(); } // Stripping //----------------------------------------------------------------------- /** * <p>Strips whitespace from the start and end of a String.</p> * * <p>This is similar to {@link #trim(String)} but removes whitespace. * Whitespace is defined by {@link Character#isWhitespace(char)}.</p> * * <p>A <code>null</code> input String returns <code>null</code>.</p> * * <pre> * StringUtils.strip(null) = null * StringUtils.strip("") = "" * StringUtils.strip(" ") = "" * StringUtils.strip("abc") = "abc" * StringUtils.strip(" abc") = "abc" * StringUtils.strip("abc ") = "abc" * StringUtils.strip(" abc ") = "abc" * StringUtils.strip(" ab c ") = "ab c" * </pre> * * @param str the String to remove whitespace from, may be null * @return the stripped String, <code>null</code> if null String input */ public static String strip(String str) { return strip(str, null); } /** * <p>Strips whitespace from the start and end of a String returning * <code>null</code> if the String is empty ("") after the strip.</p> * * <p>This is similar to {@link #trimToNull(String)} but removes whitespace. * Whitespace is defined by {@link Character#isWhitespace(char)}.</p> * * <pre> * StringUtils.stripToNull(null) = null * StringUtils.stripToNull("") = null * StringUtils.stripToNull(" ") = null * StringUtils.stripToNull("abc") = "abc" * StringUtils.stripToNull(" abc") = "abc" * StringUtils.stripToNull("abc ") = "abc" * StringUtils.stripToNull(" abc ") = "abc" * StringUtils.stripToNull(" ab c ") = "ab c" * </pre> * * @param str the String to be stripped, may be null * @return the stripped String, * <code>null</code> if whitespace, empty or null String input * @since 2.0 */ public static String stripToNull(String str) { if (str == null) { return null; } str = strip(str, null); return str.length() == 0 ? null : str; } /** * <p>Strips whitespace from the start and end of a String returning * an empty String if <code>null</code> input.</p> * * <p>This is similar to {@link #trimToEmpty(String)} but removes whitespace. * Whitespace is defined by {@link Character#isWhitespace(char)}.</p> * * <pre> * StringUtils.stripToEmpty(null) = "" * StringUtils.stripToEmpty("") = "" * StringUtils.stripToEmpty(" ") = "" * StringUtils.stripToEmpty("abc") = "abc" * StringUtils.stripToEmpty(" abc") = "abc" * StringUtils.stripToEmpty("abc ") = "abc" * StringUtils.stripToEmpty(" abc ") = "abc" * StringUtils.stripToEmpty(" ab c ") = "ab c" * </pre> * * @param str the String to be stripped, may be null * @return the trimmed String, or an empty String if <code>null</code> input * @since 2.0 */ public static String stripToEmpty(String str) { return str == null ? EMPTY : strip(str, null); } /** *找出str不存在于stripChars的字符返回(该定义不严谨,请分析代码理解) * <pre> * StringUtils.strip(null, *) = null * StringUtils.strip("", *) = "" * StringUtils.strip("abc", null) = "abc" * StringUtils.strip(" abc", null) = "abc" * StringUtils.strip("abc ", null) = "abc" * StringUtils.strip(" abc ", null) = "abc" * StringUtils.strip(" abcyx", "xyz") = " abc" * </pre> * */ public static String strip(String str, String stripChars) { if (isEmpty(str)) { return str; } str = stripStart(str, stripChars); return stripEnd(str, stripChars); } /** *对str从前向后进行逐个字符查找,找到第一个不存在stripChars的字符,然后把str中从该字符向后的字符串返回。 * <pre> * StringUtils.stripStart(null, *) = null * StringUtils.stripStart("", *) = "" * StringUtils.stripStart("abc", "") = "abc" * StringUtils.stripStart("abc", null) = "abc" * StringUtils.stripStart(" abc", null) = "abc" * StringUtils.stripStart("abc ", null) = "abc " * StringUtils.stripStart(" abc ", null) = "abc " * StringUtils.stripStart("yxabc ", "xyz") = "abc " a是第一个在“xyz"中找不到的字符,所以返回"abc" * </pre> */ public static String stripStart(String str, String stripChars) { int strLen; if (str == null || (strLen = str.length()) == 0) { return str; } int start = 0; if (stripChars == null) { while ((start != strLen) && Character.isWhitespace(str.charAt(start))) { start++; } } else if (stripChars.length() == 0) { return str; } else { while ((start != strLen) && (stripChars.indexOf(str.charAt(start)) != INDEX_NOT_FOUND)) { start++; } } return str.substring(start); } /** *对str从后向前进行逐个字符查找,找到第一个不存在stripChars的字符,然后把str中从该字符向后的字符串返回。 * <pre> * StringUtils.stripEnd(null, *) = null * StringUtils.stripEnd("", *) = "" * StringUtils.stripEnd("abc", "") = "abc" * StringUtils.stripEnd("abc", null) = "abc" * StringUtils.stripEnd(" abc", null) = " abc" * StringUtils.stripEnd("abc ", null) = "abc" * StringUtils.stripEnd(" abc ", null) = " abc" * StringUtils.stripEnd(" abcyx", "xyz") = " abc" * StringUtils.stripEnd("120.00", ".0") = "12" * </pre> * * @param str the String to remove characters from, may be null * @param stripChars the set of characters to remove, null treated as whitespace * @return the stripped String, <code>null</code> if null String input */ public static String stripEnd(String str, String stripChars) { int end; if (str == null || (end = str.length()) == 0) { return str; } if (stripChars == null) { while ((end != 0) && Character.isWhitespace(str.charAt(end - 1))) { end--; } } else if (stripChars.length() == 0) { return str; } else { while ((end != 0) && (stripChars.indexOf(str.charAt(end - 1)) != INDEX_NOT_FOUND)) { end--; } } return str.substring(0, end); } // StripAll //----------------------------------------------------------------------- /** * * <p>A new array is returned each time, except for length zero. * A <code>null</code> array will return <code>null</code>. * An empty array will return itself. * A <code>null</code> array entry will be ignored.</p> * *每次返回一个新数组,除非原数组的长度为0 *如果参数为null则返回null *如果一个空的数组返回他自己[] *数组中元素为null的不进行处理,依旧为null返回。 * <pre> * StringUtils.stripAll(null) = null * StringUtils.stripAll([]) = [] * StringUtils.stripAll(["abc", " abc"]) = ["abc", "abc"] * StringUtils.stripAll(["abc ", null]) = ["abc", null] * </pre> */ public static String[] stripAll(String[] strs) { return stripAll(strs, null); } /** * 不说了,和上面一样 * <pre> * StringUtils.stripAll(null, *) = null * StringUtils.stripAll([], *) = [] * StringUtils.stripAll(["abc", " abc"], null) = ["abc", "abc"] * StringUtils.stripAll(["abc ", null], null) = ["abc", null] * StringUtils.stripAll(["abc ", null], "yz") = ["abc ", null] * StringUtils.stripAll(["yabcz", null], "yz") = ["abc", null] * </pre> */ public static String[] stripAll(String[] strs, String stripChars) { int strsLen; if (strs == null || (strsLen = strs.length) == 0) { return strs; } String[] newArr = new String[strsLen]; for (int i = 0; i < strsLen; i++) { //调用strip进行前后循环查找 newArr[i] = strip(strs[i], stripChars); } return newArr; } // Equals //----------------------------------------------------------------------- /** * <p>Compares two Strings, returning <code>true</code> if they are equal.</p> * * <p><code>null</code>s are handled without exceptions. Two <code>null</code> * references are considered to be equal. The comparison is case sensitive.</p> * * <pre> * StringUtils.equals(null, null) = true * StringUtils.equals(null, "abc") = false * StringUtils.equals("abc", null) = false * StringUtils.equals("abc", "abc") = true * StringUtils.equals("abc", "ABC") = false * </pre> * * @see java.lang.String#equals(Object) * @param str1 the first String, may be null * @param str2 the second String, may be null * @return <code>true</code> if the Strings are equal, case sensitive, or * both <code>null</code> */ public static boolean equals(String str1, String str2) { //如果连个参数都为null则返回true,否则调用String的equals进行内容判断。 /*java.lang.String.equals(Object anObject): * Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object. 把String和指定的String 对象进行比较 当且仅当参数不为null且字 符 串 序 列(注意是相同的字符串序列)相同时返回true */ return str1 == null ? str2 == null : str1.equals(str2); } /** * <p>Compares two Strings, returning <code>true</code> if they are equal ignoring * the case.</p> *忽略大小写进行比较 * * <pre> * StringUtils.equalsIgnoreCase(null, null) = true * StringUtils.equalsIgnoreCase(null, "abc") = false * StringUtils.equalsIgnoreCase("abc", null) = false * StringUtils.equalsIgnoreCase("abc", "abc") = true * StringUtils.equalsIgnoreCase("abc", "ABC") = true * </pre> */ public static boolean equalsIgnoreCase(String str1, String str2) { return str1 == null ? str2 == null : str1.equalsIgnoreCase(str2); } // IndexOf //----------------------------------------------------------------------- /** * <p>Finds the first index within a String, handling <code>null</code>. * This method uses {@link String#indexOf(int)}.</p> *返回指定字符串的起始位置,如果被查找字符串为“”或者null则返回-1。找不到时也返回-1 * * <p>A <code>null</code> or empty ("") String will return <code>INDEX_NOT_FOUND (-1)</code>.</p> * * <pre> * StringUtils.indexOf(null, *) = -1 * StringUtils.indexOf("", *) = -1 * StringUtils.indexOf("aabaabaa", 'a') = 0 * StringUtils.indexOf("aabaabaa", 'b') = 2 * </pre> */ public static int indexOf(String str, char searchChar) { if (isEmpty(str)) { return INDEX_NOT_FOUND; } return str.indexOf(searchChar); } /** * <p>Finds the first index within a String from a start position, * handling <code>null</code>. * This method uses {@link String#indexOf(int, int)}.</p> * * <p>A <code>null</code> or empty ("") String will return <code>(INDEX_NOT_FOUND) -1</code>. * A negative start position is treated as zero. * A start position greater than the string length returns <code>-1</code>.</p> *指定查找的起始位置 *当起始位置为0时不进行处理 *起始位置大于字符串长度时返回-1 * * <pre> * StringUtils.indexOf(null, *, *) = -1 * StringUtils.indexOf("", *, *) = -1 * StringUtils.indexOf("aabaabaa", 'b', 0) = 2 * StringUtils.indexOf("aabaabaa", 'b', 3) = 5 * StringUtils.indexOf("aabaabaa", 'b', 9) = -1 * StringUtils.indexOf("aabaabaa", 'b', -1) = 2 * </pre> * * @param str the String to check, may be null * @param searchChar the character to find * @param startPos the start position, negative treated as zero * @return the first index of the search character, * -1 if no match or <code>null</code> string input * @since 2.0 */ public static int indexOf(String str, char searchChar, int startPos) { if (isEmpty(str)) { return INDEX_NOT_FOUND; } return str.indexOf(searchChar, startPos); } /** * <p>Finds the first index within a String, handling <code>null</code>. * This method uses {@link String#indexOf(String)}.</p> * * <p>A <code>null</code> String will return <code>-1</code>.</p> * * <pre> * StringUtils.indexOf(null, *) = -1 * StringUtils.indexOf(*, null) = -1 * StringUtils.indexOf("", "") = 0 * StringUtils.indexOf("", *) = -1 (except when * = "") * StringUtils.indexOf("aabaabaa", "a") = 0 * StringUtils.indexOf("aabaabaa", "b") = 2 * StringUtils.indexOf("aabaabaa", "ab") = 1 * StringUtils.indexOf("aabaabaa", "") = 0 * </pre> * * @param str the String to check, may be null * @param searchStr the String to find, may be null * @return the first index of the search String, * -1 if no match or <code>null</code> string input * @since 2.0 */ public static int indexOf(String str, String searchStr) { if (str == null || searchStr == null) { return INDEX_NOT_FOUND; } return str.indexOf(searchStr); } /** * <p>Finds the n-th index within a String, handling <code>null</code>. * This method uses {@link String#indexOf(String)}.</p> * * <p>A <code>null</code> String will return <code>-1</code>.</p> * * <pre> * StringUtils.ordinalIndexOf(null, *, *) = -1 * StringUtils.ordinalIndexOf(*, null, *) = -1 * StringUtils.ordinalIndexOf("", "", *) = 0 * StringUtils.ordinalIndexOf("aabaabaa", "a", 1) = 0 * StringUtils.ordinalIndexOf("aabaabaa", "a", 2) = 1 * StringUtils.ordinalIndexOf("aabaabaa", "b", 1) = 2 * StringUtils.ordinalIndexOf("aabaabaa", "b", 2) = 5 * StringUtils.ordinalIndexOf("aabaabaa", "ab", 1) = 1 * StringUtils.ordinalIndexOf("aabaabaa", "ab", 2) = 4 * StringUtils.ordinalIndexOf("aabaabaa", "", 1) = 0 * StringUtils.ordinalIndexOf("aabaabaa", "", 2) = 0 * </pre> * * <p>Note that 'head(String str, int n)' may be implemented as: </p> * * <pre> * str.substring(0, lastOrdinalIndexOf(str, "\n", n)) * </pre> * * @param str the String to check, may be null * @param searchStr the String to find, may be null * @param ordinal the n-th <code>searchStr</code> to find * @return the n-th index of the search String, * <code>-1</code> (<code>INDEX_NOT_FOUND</code>) if no match or <code>null</code> string input * @since 2.1 */ public static int ordinalIndexOf(String str, String searchStr, int ordinal) { return ordinalIndexOf(str, searchStr, ordinal, false); }
-------------------------------------------------------------