从事JAVA开发这么久,很多时候需要一些有用的工具包的协助,对于开发而言效率很高。最开始接触JAVA的时候,遇到一些简单的操作比如文件的复制删除,字符串的判断还有就是读取文件内容这些都是可以用工具类来实现的,并不一定非要你用原生的文件流操作,然而,如果仅仅是用而不知道其中的原理也是不可取的,对于这些工具类,最好是在阅读其源码的基础上进行理解,然后才是应用。
在Java中,工具类定义了一组公共方法,Java中使用最频繁及最通用的Java工具类。

  • 附有代码的是我觉得比较重要但是容易被忽视的方法,一些简单的常用的比如StringUtils.isBlank 方法由于经常使用故没有附上代码。

org.apache.commons.lang.StringUtils (字符串的工具类)

isBlank:字符串是否为空 (trim后判断)

isEmpty:字符串是否为空 (不trim并判断)

equals:字符串是否相等

join:合并数组为单一字符串,可传分隔符

split:分割字符串

EMPTY:返回空字符串

trimToNull:trim后为空字符串则转换为null

replace:替换字符串

org.apache.commons.lang3.StringUtils

capitalize:首字符大写

  • 代码
/*
 * 【Author】 爱吃早餐的程序员
 * 【Time】2020年11月20日 下午5:43:25
 * 【Function】
 */
public class Test1 {
	public static void main(String[] args) {
		boolean equals = StringUtils.equals("1", "3");
		System.out.println(equals);
		ArrayList<Object> arrayList = new ArrayList<>();
		arrayList.add("1");
		arrayList.add("2");
		String join = StringUtils.join(arrayList, ",");
		System.out.println(join);
		String replace = StringUtils.replace("宋江", "宋", "李双");
		System.out.println(replace);
		String capitalise = StringUtils.capitalise("abort");
		System.out.println(capitalise);
	}
}
  • 输出
false
1,2
李双江
Abort

org.springframework.util.StringUtils

hasText:检查字符串中是否包含文本

hasLength:检测字符串是否长度大于0

isEmpty:检测字符串是否为空(若传入为对象,则判断对象是否为null)

commaDelimitedStringToArray:逗号分隔的String转换为数组

collectionToDelimitedString:把集合转为CSV格式字符串

replace 替换字符串

delimitedListToStringArray:相当于split

uncapitalize:首字母小写

collectionToDelimitedCommaString:把集合转为CSV格式字符串

tokenizeToStringArray:和split基本一样,但能自动去掉空白的单词

//org.springframework.util
	boolean hasText = org.springframework.util.StringUtils.hasText("1212");
	boolean hasText2 = org.springframework.util.StringUtils.hasText("");
	System.out.println(hasText+"=="+hasText2);
	String[] commaDelimitedListToStringArray = org.springframework.util.StringUtils.commaDelimitedListToStringArray("我爱你");
	System.out.println(commaDelimitedListToStringArray.toString());
	for (String string : commaDelimitedListToStringArray) {
		System.out.println(string);
	}
	String collectionToDelimitedString = org.springframework.util.StringUtils.collectionToDelimitedString(arrayList, ":");
	System.out.println(collectionToDelimitedString);

org.apache.commons.lang.ArrayUtils

contains:是否包含某字符串

addAll:添加整个数组

clone:克隆一个数组

isEmpty:是否空数组

add:向数组添加元素

subarray:截取数组

indexOf:查找某个元素的下标

isEquals:比较数组是否相等

toObject:基础类型数据数组转换为对应的Object数组

/*
 * 【Author】 爱吃早餐的程序员
 * 【Time】2020年11月20日 下午6:02:20
 * 【Function】
 */
public class Test2 {
	public static void main(String[] args) {
		Object[] array =  new Object[]{1,2};
		boolean contains = ArrayUtils.contains(array , 1);
		System.out.println(contains);
		int[] ints =  new int[] {1,2};
		int[] clone = ArrayUtils.clone(ints);
		System.out.println(clone);
		System.out.println(ints);
		System.out.println(clone == ints); // 地址值不等
		boolean equals = ArrayUtils.isEquals(ints, clone); // 值相等
		System.out.println(equals);
	}
}

org.apache.commons.lang3.ArrayUtils

contains:是否包含某个字符串

addAll:添加整个数组

clone:克隆一个数组

isEmpty:是否空数组

add:向数组添加元素

subarray:截取数组

indexOf:查找某个元素的下标

isEquals:比较数组是否相等

toObject:基础类型数据数组转换为对应的Object数组

org.apache.commons.io.FileUtils

deleteDirectory:删除文件夹

readFileToString:以字符形式读取文件内容

deleteQueitly:删除文件或文件夹且不会抛出异常

copyFile:复制文件

writeStringToFile:把字符写到目标文件,如果文件不存在,则创建

forceMkdir:强制创建文件夹,如果该文件夹父级目录不存在,则创建父级

write:把字符写到指定文件中

listFiles:列举某个目录下的文件(根据过滤器)

copyDirectory:复制文件夹

forceDelete:强制删除文件

/*
 * 【Author】 爱吃早餐的程序员
 * 【Time】2020年11月20日 下午6:10:34
 * 【Function】
 */
public class Test3 {
	public static void main(String[] args) throws IOException {
		File file = new File("C:\\Users\\Administrator\\Desktop\\1.txt");
		String readFileToString = FileUtils.readFileToString(file);
		System.out.println(readFileToString);
		File file2 = new File("C:\\Users\\Administrator\\Desktop\\2.txt");
		FileUtils.copyFile(file, file2);
		FileUtils.writeStringToFile(file2, "答: 我不傻"); // 会覆盖里面的文字
		FileUtils.deleteQuietly(file);
	}
}

org.apache.commons.io.IOUtils

closeQuietly:关闭一个IO流、socket、或者selector且不抛出异常,通常放在finally块

toString:转换IO流、 Uri、 byte[]为String

copy:IO流数据复制,从输入流写到输出流中,最大支持2GB

toByteArray:从输入流、URI获取byte[]

write:把字节. 字符等写入输出流

toInputStream:把字符转换为输入流

readLines:从输入流中读取多行数据,返回List

copyLarge:同copy,支持2GB以上数据的复制

lineIterator:从输入流返回一个迭代器,根据参数要求读取的数据量,全部读取,如果数据不够,则失败

/*
 * 【Author】 爱吃早餐的程序员
 * 【Time】2020年11月20日 下午6:16:26
 * 【Function】
 */
public class Test4 {
	public static void main(String[] args) throws IOException {
		File file2 = new File("C:\\Users\\Administrator\\Desktop\\2.txt");
		String string = IOUtils.toString("test".getBytes());
		System.out.println(string);
		Writer output = new FileWriter(file2);
		IOUtils.write("test".getBytes(), output , "utf-8");
	    output.write("111111111");
	    output.close(); // 不可缺少  否则不生效
	    List<String> readLines = FileUtils.readLines(file2);
	    for (String string2 : readLines) {
			System.out.println(string2);
		}    		
	}
}

org.apache.http.util.EntityUtils

toString:把Entity转换为字符串

consume:确保Entity中的内容全部被消费。可以看到源码里又一次消费了Entity的内容,假如用户没有消费,那调用Entity时候将会把它消费掉

toByteArray:把Entity转换为字节流

consumeQuietly:和consume一样,但不抛异常

getContentCharset:获取内容的编码

HttpEntity entity= new StringEntity("111","utf-8");
		ByteArrayEntity byteArrayEntity = new ByteArrayEntity("test".getBytes());
		try {
			String string = EntityUtils.toString(entity);
			String stringbyteArrayEntity = EntityUtils.toString(byteArrayEntity);
			System.out.println(string);
			System.out.println(stringbyteArrayEntity);
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		try {
			byte[] array = EntityUtils.toByteArray(entity);
			System.out.println(array.length);
		} catch (IOException e) {
			e.printStackTrace();
		}
		String contentCharSet = EntityUtils.getContentCharSet(entity);
		System.out.println(contentCharSet);
	}
  • 结果
111
test
3
UTF-8

org.apache.commons.io.FilenameUtils

getExtension:返回文件后缀名

getBaseName:返回文件名,不包含后缀名

getName:返回文件全名

concat:按命令行风格组合文件路径(详见方法注释)

removeExtension:删除后缀名

normalize:使路径正常化

wildcardMatch:匹配通配符

seperatorToUnix:路径分隔符改成unix系统格式的,即/

getFullPath:获取文件路径,不包括文件名

isExtension:检查文件后缀名是不是传入参数(List)中的一个

public static void main(String[] args) {
		String extension = FilenameUtils.getExtension("1..pdf");
		String getBaseName = FilenameUtils.getBaseName("1..pdf");
		String getBaseName2 = FilenameUtils.getBaseName("1.*pdf");
		String getExtension2 = FilenameUtils.getExtension("1.*pdf");
		System.out.println(extension+"=="+getBaseName+"==="+getExtension2+"=="+getBaseName2); // 他底层的原理是查询最后的一个"."来截取的
		String removeExtension = FilenameUtils.removeExtension("1.pdf");
		System.out.println(removeExtension);
		String normalize = FilenameUtils.normalize("/1/1.pdf"); // 没啥用
		System.out.println(normalize);
		String fullPath = FilenameUtils.getFullPath("/a/b/1.pdf");
		System.out.println("fullPath:"+fullPath);
		boolean extension2 = FilenameUtils.isExtension("1.pdf", "pdf");
		boolean extension3 = FilenameUtils.isExtension("1.pdf", "jpg");
		System.out.println(extension2);
		System.out.println(extension3);
	}
  • 结果
pdf==1.===*pdf==1
1
\1\1.pdf
fullPath:/a/b/
true
false

org.apache.http.client.utils.URLEncodedUtils

format:格式化参数,返回一个HTTP POST或者HTTP PUT可用application/x-www-form-urlencoded字符串

parse:把String或者URI等转换为List

List<NameValuePair> parse = URLEncodedUtils.parse("111:22", Charset.defaultCharset());
		List<NameValuePair> parse2 = URLEncodedUtils.parse("123$456", Charset.defaultCharset(), '$');
		for (NameValuePair nameValuePair : parse) {
			System.out.println(nameValuePair.getName()+"=="+nameValuePair.getValue());
		}
		for (NameValuePair nameValuePair : parse2) {
			System.out.println(nameValuePair.getName()+"=="+nameValuePair.getValue());
		}
  • 结果
123==null
456==null

org.apache.commons.codec.digest.DigestUtils

md5Hex:MD5加密,返回32位字符串

sha1Hex:SHA-1加密

sha256Hex:SHA-256加密

sha512Hex:SHA-512加密

md5:MD5加密,返回16位字符串

public static void main(String[] args) {
		String md5Hex = DigestUtils.md5Hex("你妹的");
		System.out.println(md5Hex);
		String sha1Hex = DigestUtils.sha1Hex("你妹的");
		System.out.println(sha1Hex);
		String sha256Hex = DigestUtils.sha256Hex("你妹的");
		System.out.println(sha256Hex);
		String sha512Hex = DigestUtils.sha512Hex("你妹的");
		System.out.println(sha512Hex);
	}
  • 结果
3b4894d183aa248adf759ff98a8a33b4
0113282d5b38b40f39cbab96d338c4b37a3f0dee
55798a3913aa55559406bf85e5f67339ab3db8fcad09ea85a73c8007bb0cbf72
727f7c42ec63da655fc918bbd24a8afcd41b740cf3e51df5bdf18b6d3a14c89cd765d0ca5e7f395df743f884de12a0036391e8d14191dfa0b82f137e519b0304

org.apache.commons.collections.CollectionUtils

isEmpty:是否为空

select:根据条件筛选集合元素

transform:根据指定方法处理集合元素,类似List的map()

filter:过滤元素,雷瑟List的filter()

find:基本和select一样

collect:和transform 差不多一样,但是返回新数组

forAllDo:调用每个元素的指定方法

isEqualCollection:判断两个集合是否一致

public static void main(String[] args) {
		HashSet<String> hashSet = new HashSet<String>();
		boolean empty = CollectionUtils.isEmpty(hashSet);
		hashSet.add("222");
		hashSet.add("111");
		hashSet.add("333");
		boolean empty2 = CollectionUtils.isEmpty(hashSet);
		System.out.println(empty);
		System.out.println(empty2);
		CollectionUtils.select(hashSet, ele -> ((String)ele).contains("2"))
			.forEach(ele -> System.out.println(ele)); // jdk 1.8
		
		CollectionUtils.transform(hashSet, new Transformer() {
			@Override
			public Object transform(Object input) {
				// 将每个集合元素增加一个时间戳的后缀
				input = input.toString()+"-"+System.currentTimeMillis()+"";
				return input;
			}
		});
		for (String string : hashSet) {
			System.err.println(string);
		}
		CollectionUtils.forAllDo(hashSet, new Closure() {
			@Override
			public void execute(Object input) {
				if (input.toString().contains("222")) {
					System.out.println("=="+input);
				}
			}
		});
		boolean equalCollection = CollectionUtils.isEqualCollection(hashSet, hashSet);
		HashSet<String> set = new HashSet<String>();
		boolean equalCollection2 = CollectionUtils.isEqualCollection(hashSet,set );
		System.out.println(equalCollection+"==="+equalCollection2);
		
	}
  • 结果
true
false
222
222-1605927893112
111-1605927893112
333-1605927893112
==222-1605927893112
true===false

org.apache.commons.beanutils.PropertyUtils

getProperty:获取对象属性值

setProperty:设置对象属性值

getPropertyDiscriptor:获取属性描述器

isReadable:检查属性是否可访问

copyProperties:复制属性值,从一个对象到另一个对象

getPropertyDiscriptors:获取所有属性描述器

isWriteable:检查属性是否可写

getPropertyType:获取对象属性类型

org.apache.commons.lang3.StringEscapeUtils

unescapeHtml4:转义html

escapeHtml4:反转义html

escapeXml:转义xml

unescapeXml:反转义xml

escapeJava:转义unicode编码

escapeEcmaScript:转义EcmaScript字符

unescapeJava:反转义unicode编码

escapeJson:转义json字符

escapeXml10:转义Xml10

这个现在已经废弃了,建议使用commons-text包里面的方法。

org.apache.commons.beanutils.BeanUtils

copyPeoperties:复制属性值,从一个对象到另一个对象

getProperty:获取对象属性值

setProperty:设置对象属性值

populate:根据Map给属性复制

copyPeoperty:复制单个值,从一个对象到另一个对象

cloneBean:克隆bean实例

java的实用工具类库 java中常用的工具类_基础

  • 最后一个报错,不知什么原因,有没有小伙伴用过这个方法呢?