平常工作经常用到hutool工具包,久而久之我就把这些方法慢慢记录下来了,可以简单看一下
单独的工具方法
public class ExceptionUtil {
public static String toString(Exception e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
return sw.toString();
}
}
Exception具体报错内容转string
public static void main(String[] args) {
try {
int i = 1/0;
} catch (Exception e) {
System.out.println(ExceptionUtil.stacktraceToString(e));
}
}
打印出来的内容:
java.lang.ArithmeticException: / by zero
at com.bofei.activity.task.LoanActiveTask.main(LoanActiveTask.java:147)
对象List切割
按照批次分割数组,如1000个元素分四批
List<List<LoanInfoBulkChargeVO>> batchTotalList = ListUtil.splitAvg(collect, bulkDeductionBatchTotal)
按照数量分割数组,如2000个元素按200为一个组进行划分
// 按照200为一组进行划分
List<List<Integer>> resultList = ListUtil.split(originalList, 200)
对两个list队列内元素做交并集操作
public static void main(String[] args) {
List list1 = new ArrayList<String>();
list1.add("a");
list1.add("b");
list1.add("c");
List list2 = new ArrayList<String>();
list2.add("b");
list2.add("c");
list2.add("d");
List<String> intersection = (List<String>) CollUtil.intersection(list1, list2);
System.out.println("交集:" + intersection);
List<String> difference = (List<String>) CollUtil.subtract(list1, list2);
System.out.println("差集:" + difference);
List<String> union = (List<String>) CollUtil.union(list1, list2);
System.out.println("并集:" + union);
boolean isEqual = CollUtil.isEqualList(list1, list2);
System.out.println("是否完全相同:" + isEqual);
boolean isSameCollection = list1.containsAll(list2);
System.out.println("两个集合是否完全相同:" + isSameCollection);
}
交集:[b, c]
差集:[a]
并集:[a, b, c, d]
是否完全相同:false
两个集合是否完全相同:true
List < entity >对象元素转换List < entityVO >
public static void main(String[] args) {
List<EmergencyContact> personList = new ArrayList<>();
personList.add(EmergencyContact.builder().phone("123").build());
personList.add(EmergencyContact.builder().phone("456").build());
personList.add(EmergencyContact.builder().phone("789").build());
List<EmergencyContact> personList2 = new ArrayList<>();
personList2.add(EmergencyContact.builder().phone("123").build());
personList2.add(EmergencyContact.builder().phone("456").build());
personList2.add(EmergencyContact.builder().phone("789").build());
List<EmergencyContactVO> personVOList1 = BeanUtil.copyToList(personList, EmergencyContactVO.class);
List<EmergencyContactVO> personVOList2 = BeanUtil.copyToList(personList2, EmergencyContactVO.class);
for (EmergencyContactVO personVO : personVOList1) {
System.out.println(personVO.getPhone() + " - " + personVOList1.containsAll(personVOList2));
}
}
123 - true
456 - true
789 - true
数值、对象比较
System.out.println(ObjectUtil.equal(1, "1"));
System.out.println(ObjectUtil.equal(1, 1));
System.out.println(ObjectUtil.equal("", " "));
System.out.println(ObjectUtil.equal(null, " "));
System.out.println(ObjectUtil.equal(null, ""));
System.out.println(ObjectUtil.equal(Integer.parseInt("1000001"), 1000001));
System.out.println(ObjectUtil.equal(Integer.parseInt("1000001"), Integer.parseInt("1000001")));
User user = new User();
User user1 = new User();
System.out.println(ObjectUtil.equal(user, user1));
user.setAge(23);
System.out.println(ObjectUtil.equal(user, user1));
user1.setAge(23);
System.out.println(ObjectUtil.equal(user, user1));
日期转换
//1.日期转换
String dateStr = "2020-01-23T12:23:56"
DateTime dt = DateUtil.parse(dateStr)
//Date对象转LocalDateTime
LocalDateTime of = LocalDateTimeUtil.of(dt)
//时间戳转为LocalDateTime
of = LocalDateTimeUtil.ofUTC(dt.getTime())
日期字符串解析
//解析ISO时间
LocalDateTime localDateTime = LocalDateTimeUtil.parse("2020-01-23T12:23:56")
//解析自定义格式时间 转成ISO时间
localDateTime = LocalDateTimeUtil.parse("2020-01-23",DatePattern.NORM_DATE_PATTERN)
//转化为LocalDate
LocalDate localDate = LocalDateTimeUtil.parseDate("2020-01-23")
//解析日期时间为LocalDate,时间部分舍弃
localDate = LocalDateTimeUtil.parseDate("2020-01-23T12:23:56", DateTimeFormatter.ISO_DATE_TIME)
日期格式化(最常用)
LocalDateTime localDateTime1 = LocalDateTimeUtil.parse("2020-01-23T12:23:56")
String format = LocalDateTimeUtil.format(localDateTime, DatePattern.NORM_DATETIME_PATTERN)
String time = LocalDateTimeUtil.format(LocalDateTimeUtil.now(), DatePattern.NORM_DATETIME_PATTERN)
日期偏移
final LocalDateTime localDateTime2 = LocalDateTimeUtil.parse("2020-01-23T12:23:56")
// 增加一天 增减天数也可以用LocalDateTime中的方法
LocalDateTime offset = LocalDateTimeUtil.offset(localDateTime2, 1, ChronoUnit.DAYS)
String offsetString = LocalDateTimeUtil.format(offset,DatePattern.NORM_DATETIME_PATTERN)
计算日期间隔
LocalDateTime start = LocalDateTimeUtil.parse("2019-02-02T00:00:00")
LocalDateTime end = LocalDateTimeUtil.parse("2020-02-02T00:00:00")
Duration between = LocalDateTimeUtil.between(start, end)
//365
between.toDays()
一天的开始和结束
LocalDateTime localDateTime3 = LocalDateTimeUtil.parse("2020-01-23T12:23:56")
LocalDateTime beginOfDay = LocalDateTimeUtil.beginOfDay(localDateTime)
LocalDateTime endOfDay = LocalDateTimeUtil.endOfDay(localDateTime)
JSONUtil
创建json字符串
JSONUtil.toJsonStr可以将任意对象(Bean、Map、集合等)直接转换为JSON字符串。 如果对象是有序的Map等对象,则转换后的JSON字符串也是有序的。
SortedMap<Object, Object> sortedMap = new TreeMap<Object, Object>() {
private static final long serialVersionUID = 1L;
{
put("attributes", "a");
put("b", "b");
put("c", "c");
}};
JSONUtil.toJsonStr(sortedMap);
结果:
{"attributes":"a","b":"b","c":"c"}
如果我们想获得格式化后的JSON,则:
JSONUtil.toJsonPrettyStr(sortedMap)
结果:
{
"attributes": "a",
"b": "b",
"c": "c"
}
JSON字符串解析(读取特定字段键值)
String html = "{"name":"Something must have been changed since you leave"}"
JSONObject jsonObject = JSONUtil.parseObj(html)
jsonObject.getStr("name")
JSON转Bean
@Data
public class ADT {
private List<String> BookingCode;
}
@Data
public class Price {
private List<List<ADT>> ADT;
}
String json = "{"ADT":[[{"BookingCode":["N","N"]}]]}"
Price price = JSONUtil.toBean(json, Price.class)
//
price.getADT().get(0).get(0).getBookingCode().get(0)
JSON转List
存
List<ShopType> typeList = query().orderByAsc("sort").list();
String jsonStr = JSONUtil.toJsonStr(typeList);
stringRedisTemplate.opsForValue().set(CACHE_SHOP_TYPE_KEY,jsonStr);
取
String shopTypeJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_TYPE_KEY)
if (StrUtil.isNotBlank(shopTypeJson)) {
// 2.存在直接返回
List<ShopType> shopTypes = JSONUtil.toList(shopTypeJson, ShopType.class)
return Result.ok(shopTypes)
}
XML字符串转换为JSON
String s = "<sfzh>123</sfzh><sfz>456</sfz><name>aa</name><gender>1</gender>"
JSONObject json = JSONUtil.parseFromXml(s)
json.get("sfzh")
json.get("name")
JSON转换为XML
final JSONObject put = JSONUtil.createObj()
.set("aaa", "你好")
.set("键2", "test");
final String s = JSONUtil.toXmlStr(put);
其它方法
除了上面中常用的一些方法,JSONUtil还提供了一些JSON辅助方法:
- quote 对所有双引号做转义处理(使用双反斜杠做转义)
- wrap 包装对象,可以将普通任意对象转为JSON对象
- formatJsonStr 格式化JSON字符串,此方法并不严格检查JSON的格式正确与否
加减乘除 NumberUtil.add 针对数字类型做加法 NumberUtil.sub 针对数字类型做减法 NumberUtil.mul 针对数字类型做乘法 NumberUtil.div 针对数字类型做除法,并提供重载方法用于规定除不尽的情况下保留小数位数和舍弃方式。
以上四种运算都会将double转为BigDecimal后计算,解决float和double类型无法进行精确计算的问题。这些方法常用于商业计算。
import cn.hutool.core.codec.Base64
String source = "Base64 Encoding"
String encoded = Base64.encode(source)
String decoded = Base64.decodeStr(encoded)
文件读取
import cn.hutool.core.io.FileUtil
String content = FileUtil.readUtf8String("文件具体路径/文件名")
// String content = FileUtil.readUtf8String("D:\java_project\LogServiceImpl.java")
上传下载操作
请求并转换为字节数组
template:
url: https
@Value("${template.url}")
String fileUrl
byte[] bytes = HttpUtil.downloadBytes(fileUrl)
请求并下载到本地
@Value("${template.url}")
String fileUrl
byte[] bytes = HttpUtil.downloadFile(fileUrl,"目标文件或目录",30*1000)
@Test
public void testDateUtil(){
//使用下面这三种输出都是一样的结果
Date originalDate = new Date()
Date date = DateUtil.date()
Date date1 = DateUtil.date(Calendar.getInstance())
Date date2 = DateUtil.date(System.currentTimeMillis())
//得到字符串形式
String stringDate = DateUtil.now()
String stringToday = DateUtil.today()
//字符串转日期
Date stringToDate = DateUtil.parse(stringDate)
//格式化日期输出
String stringdate = "2022-03-16 11:55:42"
Date date3 = DateUtil.parse(stringdate)
String format = DateUtil.format(date3,"yyyy-MM-dd")
String format1 = DateUtil.formatDate(date3)
String format2 = DateUtil.formatDateTime(date3)
String format3 = DateUtil.formatTime(date3)
//获取Date对象的某个部分
int year = DateUtil.year(date)
int month = DateUtil.month(date)
Enum monthEnum = DateUtil.monthEnum(date)
//获得每天的开始时间、结束时间,每月的开始和结束时间等等 使用上面date3
Date beginOfDay = DateUtil.beginOfDay(date3)
String stringBeginOfDay = DateUtil.format(beginOfDay, DatePattern.NORM_DATETIME_FORMATTER)
Date endOfDay = DateUtil.endOfDay(date3)
/**
* 针对当前时间,提供了简化的偏移方法
* DateUtil.yesterday() //昨天
* DateUtil.tomorrow() //明天
* DateUtil.lastWeek() //上周
* DateUtil.nextWeek() //下周
* DateUtil.lastMonth() //上个月
* DateUtil.nextMonth() //下个月
*/
//日期时间偏移 日期的变更
Date newDate = DateUtil.offset(date, DateField.DAY_OF_MONTH, 2)
DateTime newDate2 = DateUtil.offsetDay(date, 3)
DateTime newDate3 = DateUtil.offsetHour(date, -3)
//日期时间差
String dateStr1 = "2017-03-01 22:33:23"
Date dateOne = DateUtil.parse(dateStr1)
String dateStr2 = "2017-04-01 23:33:23"
Date dateTwo = DateUtil.parse(dateStr2)
Long days = DateUtil.between(dateOne,dateTwo,DateUnit.MS)
//格式化时间差 上面是秒下面是毫秒 差一等级才能转换
String formatBetween = DateUtil.formatBetween(days, BetweenFormatter.Level.MILLISECOND)
//星座和属相
String zodiac = DateUtil.getZodiac(Month.JANUARY.getValue(), 19)
String chineseZodiac = DateUtil.getChineseZodiac(2022)
}
没有回复内容