java开发常用工具类(持续更新)

[TOC]

1 场景

本文主要记录java开发中,常用的外部工具类,使用这些工具类能大大提高开发的效率代码的健壮性

因为时间问题,本文将慢慢持续更新完善。

本文基于JDK1.8

2 相关maven依赖

2.1 commons-lang3

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>
</dependency>

2.2 commons-collections4

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-collections4</artifactId>
    <version>4.4</version>
</dependency>

2.3 commons-text

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-text</artifactId>
    <version>1.9</version>
</dependency>

2.4 commons-codec

<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.15</version>
</dependency>

2.5 commons-io

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.9.0</version>
</dependency>

2.6 commons-csv

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-csv</artifactId>
    <version>1.8</version>
</dependency>

3 字符串相关

3.1 JDK

相关类:java.lang.String

3.1.1 数组、集合指定分隔符分隔
String[] arr = new String[]{"1", "2", "3"};
// 转换数组,结果:1,2,3
String result1 = String.join(",", arr);

List<String> list = Stream.of(arr).collect(Collectors.toList());
// 转换集合,结果:1,2,3
String result2 = String.join(",", list);

3.2 commons-lang3包

相关类:

org.apache.commons.lang3.StringUtils

org.apache.commons.lang3.RandomStringUtils

3.2.1 字符串判空
/**
 * StringUtils.isEmpty(null)      = true
 * StringUtils.isEmpty("")        = true
 * StringUtils.isEmpty(" ")       = false
 * StringUtils.isEmpty("bob")     = false
 * StringUtils.isEmpty("  bob  ") = false
 */
boolean result = StringUtils.isEmpty(str);
boolean result = StringUtils.isNotEmpty(str);

/**
 * StringUtils.isBlank(null)      = true
 * StringUtils.isBlank("")        = true
 * StringUtils.isBlank(" ")       = true
 * StringUtils.isBlank("bob")     = false
 * StringUtils.isBlank("  bob  ") = false
 */
boolean result = StringUtils.isBlank(str);
boolean result = StringUtils.isNotEmpty(str);
3.2.2 字符串判断相等
/**
 * 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
 */
boolean result = StringUtils.equals(null, "123");
3.2.3 是否包含子字符串
/**
 * StringUtils.contains(null, *)     = false
 * StringUtils.contains(*, null)     = false
 * StringUtils.contains("", "")      = true
 * StringUtils.contains("abc", "")   = true
 * StringUtils.contains("abc", "a")  = true
 * StringUtils.contains("abc", "z")  = false
 */
boolean result = StringUtils.contains("abcd", "ab");
3.3.4 判断以某字符串开头

/**
 * StringUtils.startsWith(null, null)      = true
 * StringUtils.startsWith(null, "abc")     = false
 * StringUtils.startsWith("abcdef", null)  = false
 * StringUtils.startsWith("abcdef", "abc") = true
 * StringUtils.startsWith("ABCDEF", "abc") = false
 */
boolean result = StringUtils.startsWith("abcd","ab");
2.3.5 判断以某字符串结尾
/**
 * StringUtils.endsWith(null, null)      = true
 * StringUtils.endsWith(null, "def")     = false
 * StringUtils.endsWith("abcdef", null)  = false
 * StringUtils.endsWith("abcdef", "def") = true
 * StringUtils.endsWith("ABCDEF", "def") = false
 * StringUtils.endsWith("ABCDEF", "cde") = false
 * StringUtils.endsWith("ABCDEF", "")    = true
 */
boolean result = StringUtils.endsWith("abcd","cd");
3.3.4 补全字符串
/**
 * StringUtils.leftPad(null, *, *)      = null
 * StringUtils.leftPad("", 3, "z")      = "zzz"
 * StringUtils.leftPad("bat", 3, "yz")  = "bat"
 * StringUtils.leftPad("bat", 5, "yz")  = "yzbat"
 * StringUtils.leftPad("bat", 8, "yz")  = "yzyzybat"
 * StringUtils.leftPad("bat", 1, "yz")  = "bat"
 * StringUtils.leftPad("bat", -1, "yz") = "bat"
 * StringUtils.leftPad("bat", 5, null)  = "  bat"
 * StringUtils.leftPad("bat", 5, "")    = "  bat"
 */
// 左边补齐为5位字符串,结果:00123
String result = StringUtils.leftPad("123", 5, "0");
// 结果:123
String result = StringUtils.leftPad("123", 2, "0");

//-----------------------------
/**
 * StringUtils.rightPad(null, *, *)      = null
 * StringUtils.rightPad("", 3, "z")      = "zzz"
 * StringUtils.rightPad("bat", 3, "yz")  = "bat"
 * StringUtils.rightPad("bat", 5, "yz")  = "batyz"
 * StringUtils.rightPad("bat", 8, "yz")  = "batyzyzy"
 * StringUtils.rightPad("bat", 1, "yz")  = "bat"
 * StringUtils.rightPad("bat", -1, "yz") = "bat"
 * StringUtils.rightPad("bat", 5, null)  = "bat  "
 * StringUtils.rightPad("bat", 5, "")    = "bat  "
 */
// 右侧补齐为5位字符串,结果:12300
String result = StringUtils.rightPad("123", 5, "0");
3.3.5 反转字符串
// 结果:cba
String result = StringUtils.reverse("abc");
3.3.6 重复字符串
/**
 * StringUtils.repeat(null, 2) = null
 * StringUtils.repeat("", 0)   = ""
 * StringUtils.repeat("", 2)   = ""
 * StringUtils.repeat("a", 3)  = "aaa"
 * StringUtils.repeat("ab", 2) = "abab"
 * StringUtils.repeat("a", -2) = ""
*/
// 结果:00000
String result = StringUtils.repeat("0",5);
3.3.7 随机字符串
//10位,包含英文大小写,如:MiLdFwsrDF
System.out.println(RandomStringUtils.randomAlphabetic(10));

//10位,包含英文大小写,和数字,如:QESP1Zjqjn
System.out.println(RandomStringUtils.randomAlphanumeric(10));

//10位,ASCII码,如:Kv(f.1rC)*
System.out.println(RandomStringUtils.randomAscii(10));

//10位,指定文字,如:ceabbaecec
System.out.println(RandomStringUtils.random(10, "abcde"));

//10位,数字,如:0025228642
System.out.println(RandomStringUtils.randomNumeric(10));

3.3 commons-text包

相关类:org.apache.commons.text.StringSubstitutor

3.1.1 替换字符串占位符
Map<String, String> valueMap = new HashMap<>();
valueMap.put("name", "张三");
valueMap.put("age", "18");
// 默认替换占位符【${xxx}】,可调用构造函数【new StringSubstitutor(valueMap)】
StringSubstitutor stringSubstitutor = new StringSubstitutor(valueMap, "${", "}");
// 替换结果:姓名:张三,年龄:18。
String result = stringSubstitutor.replace("姓名:${name},年龄:${age}。");

//-------------------------
Map<String, Object> params = new HashMap<>();
params.put("jre-1.8", "java-version-1.8");
params.put("java.specification.version", "1.8");
StringSubstitutor stringSubstitutor = new StringSubstitutor(params);
// 支持变量的嵌套替换
stringSubstitutor.setEnableSubstitutionInVariables(true);
// 结果:java-version-1.8
String result = stringSubstitutor.replace("${jre-${java.specification.version}}");

4 集合相关

4.1 commons-collections4包

相关类:org.apache.commons.collections4.CollectionUtils

4.1.1 判断集合是否为空
// 非线程安全
boolean result = CollectionUtils.isEmpty(list);
boolean result = CollectionUtils.isNotEmpty(list);
4.1.2 元素加到集合中
List<String> list = new ArrayList<String>(){{add("1");add("2");}};
// 如何集合被更改,返回true,否则返回false。list内容变更为:1, 2, a, b
boolean result = CollectionUtils.addAll(list,"a","b");
// 集合追加到集合
boolean result = CollectionUtils.addAll(list1,list2);
4.1.3 反转数组
String[] arr = new String[]{"1", "2", "3"};
// arr结果为:3,2,1
CollectionUtils.reverseArray(arr);
4.1.4 合并集合
// 返回结果:判断集合是否变更
boolean result = CollectionUtils.addAll(targetList,sourceList);

5 转码

5.1 commons-codec包

相关类:

org.apache.commons.codec.digest.DigestUtils

5.1.1 MD5摘要
// 生成md5摘要(32位十六进制),返回:e10adc3949ba59abbe56e057f20f883e
String md5Hex = DigestUtils.md5Hex("123456");

// 字节数组,生成md5摘要
// public static String md5Hex(final byte[] data);

// 输入流,生成md5摘要(可用于生成文件的md5摘要)
// public static String md5Hex(final InputStream data) throws IOException;
5.1.2 SHA-1摘要
// 生成SHA-1摘要(十六进制),返回:7c4a8d09ca3762af61e59520943dc26494f8941b
String sha1 = DigestUtils.sha1Hex("123456");

// 字节数组,生成SHA-1摘要
// public static String sha1Hex(final byte[] data);

// 输入流,生成SHA-1摘要(可用于生成文件的SHA-1摘要)
// public static String sha1Hex(final InputStream data) throws IOException;

6 文件相关

6.1 commons-io包

相关类:

org.apache.commons.io.FileUtils

org.apache.commons.io.FilenameUtils

6.1 获取文件路径信息
// 获取文件名(无后缀),返回:电话区域表
String baseName = FilenameUtils.getBaseName("D:\\config\\电话区域表.xlsx");

// 获取文件名(包括后缀),返回:电话区域表.xlsx
String name = FilenameUtils.getName("D:\\config\\电话区域表.xlsx");

// 获取后缀,返回:xlsx
String extension = FilenameUtils.getExtension("D:\\config\\电话区域表.xlsx");
6.2 字符串写入文件
// 写入数据
String data = "文本数据";
// 追加写入(默认false)
boolean append = true;
// 将一个字符串写入一个文件(无换行)
FileUtils.writeStringToFile(new File("D:\\config\\test.txt"), data, Charset.forName("GBK"), append);
6.3 批量写入文件
// 集合内容
List<String> list = new ArrayList<String>(){{add("aaa");add("bbb");add("ccc");}};
// 行分隔符(默认null)
String lineEnding = null;
// 追加写入(默认false)
boolean append = false;
// 字符集名称(默认为null,采用操作系统默认值)
String charsetName = "GBK";
// 集合内的每个元素,执行toString(),按行写入文件
FileUtils.writeLines(new File("D:\\config\\test.txt"), charsetName, list, lineEnding, append);
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,088评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,715评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,361评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,099评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 60,987评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,063评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,486评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,175评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,440评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,518评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,305评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,190评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,550评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,880评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,152评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,451评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,637评论 2 335

推荐阅读更多精彩内容