Hutool

ArrayUtil

import cn.hutool.core.util.ArrayUtil;

contains() 数组中是否包含某一个值

    @Test
    public void testContains(){
        String[] strings={"red","black","orange","white"};
        System.out.println(ArrayUtil.contains(strings,"grey"));//false
        System.out.println(ArrayUtil.contains(strings,"red"));//true
    }

CollUtil

containsAll() 一个集合是否包含另一个集合的全部元素

    @Test
    public void testContainsAll(){
        List<String> list1 = new ArrayList<>();
        list1.add("str");
        list1.add("a");
        list1.add("b");
        list1.add("c");
        List<String> list2 = new ArrayList<>();
        list2.add("b");
        list2.add("c");
        boolean isContainsAll = CollUtil.containsAll(list1, list2);
        System.out.println(isContainsAll);
    }

isEmpty() 判断一个集合是不是为空

    @Test
    public void testIsEmpty(){
        List<String> list1 = new ArrayList<>();
        list1.add("str");
        list1.add("a");
        list1.add("b");
        list1.add("c");
        List list=new ArrayList();
        System.out.println(CollUtil.isEmpty(list));//true
        System.out.println(CollUtil.isEmpty(list1));//false
    }

DateUtil

import cn.hutool.core.date.DateUtil;

beginOfYear() 获取一年最开始的时间

    @Test
    public void testBeginOfYear(){
        //2021-01-01 00:00:00
        System.out.println(DateUtil.beginOfYear(new Date()));
    }

beginOfMonth() 获取当前月第一天的时期

    @Test
    public void testBeginOfMonth(){
        System.out.println(DateUtil.beginOfMonth(new Date()));//2021-07-01 00:00:00
    }

beginOfDay 获取一天最开始的时间

    @Test
    public void testBeginOfDay(){
        //2021-08-09 00:00:00
        System.out.println(DateUtil.beginOfDay(DateUtil.date()));
    }

date()获取当前时间

    @Test
    public void testDate(){
        //获取当前时间 yy-mm-dd hh::mm::ss
        System.out.println(DateUtil.date());
    }

year() 获取时间的年份

    @Test
    public void testYear(){
        System.out.println(DateUtil.year(new Date()));
    }

betweenDay(Date beginDate, Date endDate, boolean isReset) 计算时间天数差

    @Test
    public void testBetweenDay(){
        Date d1=new Date(2018,10,22);
        Date d2=new Date(2017,10,22);
        System.out.println(DateUtil.betweenDay(d1,d2,true));//365
    }
//源码:参数isReset表示为是否重置时间 beginofDay表示一天最开始的时间
  if (isReset) {
	beginDate = beginOfDay(beginDate);
	endDate = beginOfDay(endDate);
   }

between() 计算时间间隔

    @Test
    public void testBetween() throws InterruptedException {
        //DateUnit 可以用来设置时间单位的间隔
        //between(Date beginDate, Date endDate, DateUnit unit)
        Date date= new Date();
        Thread.sleep(2000);
        Date date1=new Date();
        System.out.println(DateUtil.between(date,date1, DateUnit.SECOND));//2
    }

format(Date,String) 时间格式转换

    @Test
    public void testFormat(){
        Date date=new Date();
        // DatePattern.NORM_DATE_FORMAT : yyyy-MM-dd
        //在DatePattern类中有很多的时间格式可以让我们使用
        System.out.println(DateUtil.format(date, DatePattern.NORM_DATE_FORMAT));
        //结果:2021-07-28
    }

formatDate()获取格式化日期

    @Test
    public void testFormatDate(){
        //2021-07-28
        System.out.println(DateUtil.formatDate(DateUtil.date()));
    }

parse() 自动识别时间格式

#常见格式
yyyy-MM-dd HH:mm:ss
yyyy-MM-dd
HH:mm:ss
yyyy-MM-dd HH:mm
yyyy-MM-dd HH:mm:ss.SSS
     @Test
     public void testParse(){
        String dateStr = "2017-03-01";
        //parse会自动识别一些时间格式
        System.out.println(DateUtil.parse(dateStr));//2017-03-01 00:00:00
        //也可以自定义格式
        System.out.println(DateUtil.parse(dateStr,"yyyy-MM-dd"));//2017-03-01 00:00:00
        Date date = DateUtil.parse(dateStr);
        //还可以结合format来实现时间格式化
        System.out.println(DateUtil.format(date, "yyyy/MM/dd")); //2017/03/01
    }

isSameDay() 测试两个时间是否是同一天

    @Test
    public void testIsSameDay(){
        String date1="2008-05-23";
        String date2="2009-05-23";
        //true
        System.out.println(DateUtil.isSameDay(DateUtil.parse(date1),DateUtil.parse(date1)));
        //false
        System.out.println(DateUtil.isSameDay(DateUtil.parse(date1),DateUtil.parse(date2)));
    }

endOfYear() 获取一年最后的时间

  @Test
    public void testEndOfYear(){
        //2021-12-31 23:59:59
        System.out.println(DateUtil.endOfYear(new Date()));
    }

offset() 时间偏移量

@Test
    public void testOffset(){
        Date date = DateUtil.parse("2017-03-01 22:33:23");
        //2017-03-02 22:33:23  时间偏移一天
        System.out.println(DateUtil.offset(date, DateField.DAY_OF_MONTH,1));
        //2017-03-03 22:33:23  时间偏移两天
        System.out.println(DateUtil.offsetDay(date,2));
        //2017-03-01 20:33:23  时间偏移-2小时
        System.out.println(DateUtil.offsetHour(date,-2));
        //昨天
        System.out.println(DateUtil.yesterday());
        //明天
        System.out.println(DateUtil.tomorrow());
        //上周
        System.out.println(DateUtil.lastWeek());
        //下周
        System.out.println(DateUtil.nextWeek());
        //上一个月
        System.out.println(DateUtil.lastMonth());
        //下一个月
        System.out.println(DateUtil.nextMonth());
    }
}

SpringUtil

getBean() 获取bean

使用Spring Boot时,通过依赖注入获取bean是非常方便的,
但是在工具化的应用场景下,想要动态获取bean就变得非常困难,
于是Hutool封装了Spring中Bean获取的工具类——SpringUtil。

FileUtil

isDirectory() 是不是目录

    @Test
    public void testIsDirectory(){
        String path1="D:/softInstall/QQ音乐";
        String path2="D:/softInstall/QQ音乐/高飞.mp3";
        System.out.println(FileUtil.isDirectory(path1));//true
        System.out.println(FileUtil.isDirectory(path2));//false
    }

exist() 路径是否存在

    @Test
    public void testExist(){
        String path1="D:/softInstall";
        String path2="D:/笔记/多线程.md";
        System.out.println(FileUtil.exist(path1));//true
        System.out.println(FileUtil.exist(path2));//true
    }

file() 根据绝对路径或相对路径识别文件

    @Test
    public void testFile(){
       File file=FileUtil.file("D:\\c.txt");
       File file2=FileUtil.file("D:\\a.txt");
       System.out.println(file.exists());//false
       System.out.println(file2.exists());//true
   }

mkdir()创建目录

    @Test
    public void testMkdir(){
        String path="D:/testMkdir";
        FileUtil.mkdir(path);
    }

getOutputStream() 获取一个输出流

    @Test
    public void testGetOutputStream(){
       File file=FileUtil.file("D:\\c.txt");
       OutputStream outputStream=null;
       try{
           //获取一个输出流对象,如果对象不存在,则会帮我们自动创建
           outputStream=FileUtil.getOutputStream(file);
           String contend="How are you!";
           byte[] ct = contend.getBytes();
           outputStream.write(ct);
           outputStream.flush();

       } catch (IOException e) {
           e.printStackTrace();
       }finally {
           IoUtil.close(outputStream);
       }
   }
   //程序首先获取了一个流,因为不存在这个流,于是自动创建了该流,然后将字符串写入流中对应的文件。

writeString() 将string写入文件

    @Test
    public void testWriteString(){
        String content="hello world!";
        String path = "D:/testMkdir/a.txt";
        //path指定路径下的文件如不存在,则创建
        try {
            FileUtil.writeString(content,path, CharsetUtil.UTF_8);
        }catch (IORuntimeException e){
            throw new RuntimeException("运行时异常",e);
        }
    }

cleanInvalid() 清除文件名中的在Windows下不支持的非法字符,包括: \ / : * ? " < > |

    @Test
    public void testCleanInvalid(){
        String fileName = "cleanInvalidTest \\ / : * ? \" < >  |.txt";
        fileName=FileUtil.cleanInvalid(fileName);
        //cleanInvalidTest          .txt
        System.out.println(fileName);
    }

JSONUtil

import cn.hutool.json.JSONUtil;

toBean() 将json对象转为其它示例对象

    @Test
    public void testToBean(){
        JSONObject jsonObject=new JSONObject();
        jsonObject.set("name","dong");
        jsonObject.set("sex","男");
        jsonObject.set("age","18");
        User user=JSONUtil.toBean(jsonObject,User.class);
        //User(name=dong, sex=男, age=18)
        System.out.println(user);
    }

toJsonStr() json对象转换为字符串

    @Test
    public void testToJsonStr(){
        JSONObject jsonObject=new JSONObject();
        jsonObject.set("name","dong");
        jsonObject.set("sex","男");
        jsonObject.set("age","18");
        //{"sex":"男","name":"dong","age":"18"}
        System.out.println(JSONUtil.toJsonStr(jsonObject));
    }

StrUtil

import cn.hutool.core.util.StrUtil;

hide() 脱敏

  @Test
  public void testHide() {
      String sfz="333212299878923098";
      ystem.out.println(StrUtil.hide(sfz,0,5));
      //结果:*****2299878923098
  }

length()计算字符串的长度

    @Test
    public void testLength(){
        System.out.println(StrUtil.length("love"));//4
        //相比于String.length,我们还可以这样做
        System.out.println(StrUtil.length(1==1?"yes":"no"));//3
    }

equals() 判断两个字符串是否相同

    @Test
    public void testEquals(){
        System.out.println(StrUtil.equals("DOC","pdf"));//false
        System.out.println(StrUtil.equals("DOC","DOC"));//true
    }

isNotEmpty()字符串不为空 isEmpty()——是否为空,空的定义是null,""

    @Test
    public void testIsNotEmpty(){
        System.out.println(StrUtil.isNotEmpty(""));//false
        System.out.println(StrUtil.isNotEmpty(null));//false
        System.out.println(StrUtil.isNotEmpty("love"));//true
        System.out.println(StrUtil.isNotEmpty(" "));//true
    }

isNotBlank()字符串不为空 isBlank()——是否为空白,空白的定义是null,"",不可见字符(如空格)

    @Test
    public void testIsNotBlank(){
        System.out.println(StrUtil.isNotBlank(""));//false
        System.out.println(StrUtil.isNotBlank(null));//false
        System.out.println(StrUtil.isNotBlank("love"));//true
        System.out.println(StrUtil.isNotBlank(" "));//false
    }

format 格式转换

   @Test
    public void testFormat(){
        String keyTemplate = "{}-{}-{}";
        String keyTemplate2 = "{}爱{}";
        //dd-aa-bb
        System.out.println(StrUtil.format(keyTemplate,"dd","aa","bb"));
        //我爱你
        System.out.println(StrUtil.format(keyTemplate2,"我","你"));
    }

containsAny(CharSequence str, CharSequence... testStrs) 第一个字符的子字符串中只要一个和后面的字符串相同就返回true

    @Test
    public void testContainsAny(){
        System.out.println(StrUtil.containsAny("abc","a","b"));//true
        System.out.println(StrUtil.containsAny("abc","ac","bd"));//false
        System.out.println(StrUtil.containsAny("a","b","c"));//false
    }

containsIgnoreCase() 忽略大小写,第一个字符串的内容是否包含第二个字符串

   @Test
    public void testContainsIgnoreCase(){
        System.out.println(StrUtil.containsIgnoreCase("abc","a"));//true
        System.out.println(StrUtil.containsIgnoreCase("abc","A"));//true
        System.out.println(StrUtil.containsIgnoreCase("abc","ac"));//false
        System.out.println(StrUtil.containsIgnoreCase("a","b"));//false
    }

join() 连接字符串

    //通过第一个参数字符串,连接后面的字符串
    @Test
    public void testJoin(){
        //2008/05/12
        System.out.println(StrUtil.join("/","2008","05","12"));
        //我们还可以用来设置文件保存目录
        String filePath="D:"+StrUtil.join(File.separator,"电影","恐怖");
        System.out.println(filePath);//D:电影\恐怖
    }

ThreadUtil

import cn.hutool.core.thread.ThreadUtil;

newExecutor() 获得一个新的线程池

    @Test
    public void testExecutor(){
        //初始化线程池,同时执行5个线程
        ExecutorService executor = ThreadUtil.newExecutor(5);
        //执行线程
        executor.execute(() -> {
            for (int i = 0; i < 4; i++) {
                //打印当前线程名字
                System.out.println("当前执行线程:" +new Thread().getName());
            }
        });
        executor.shutdown();
    }
当前执行线程:Thread-0
当前执行线程:Thread-1
当前执行线程:Thread-2
当前执行线程:Thread-3

execute() 直接在公共线程池中执行线程

    @Test
    public  void testExecute(){
        //使用默认线程池GlobalThreadPool执行的
        ThreadUtil.execute(()->{
            //打印当前线程名字
            for (int i = 0; i < 4; i++) {
                System.out.println("当前线程名字"+new Thread().getName());
            }
        });
    }
当前线程名字Thread-0
当前线程名字Thread-1
当前线程名字Thread-2
当前线程名字Thread-3

sleep()

挂起当前线程,是Thread.sleep的封装,通过返回boolean值表示是否被打断,而不是抛出异常。

safeSleep() 安全睡眠

ThreadUtil.safeSleep方法是一个保证挂起足够时间的方法,
当给定一个挂起时间,使用此方法可以保证挂起的时间大于或等于给定时间,
解决Thread.sleep挂起时间不足问题,此方法在Hutool-cron的定时器中使用保证定时任务执行的准确性。

BeanUtil

import cn.hutool.core.bean.BeanUtil;

copyProperties() 复制对象

    @Test
    public void testCopyProperties(){
        User user=new User();
        user.setAge(18);
        user.setName("dong");
        user.setSex("女");

        User user1=new User();
        BeanUtil.copyProperties(user,user1);
        System.out.println(user1);//User(name=dong, sex=女, age=18)
        System.out.println(user1==user);//false
    }

IoUtil

copyByNIO() 文件拷贝

    @Test
    public void testCopyByNIO(){
       OutputStream out = null;
       InputStream in = null;
       try {
           byte[] bytes="how are you".getBytes();
           File file=FileUtil.file("D:\\f.txt");
           in = new ByteArrayInputStream(bytes);
           out = FileUtil.getOutputStream(file);
           IoUtil.copyByNIO(in, out, IoUtil.DEFAULT_BUFFER_SIZE, null);
       } finally {
           IoUtil.close(out);
           IoUtil.close(in);
       }
   }
  //程序最后创建了一个f.txt文件,并把输出流的内容写到文件中了

close() 关闭流

对于IO操作来说,使用频率最高(也是最容易被遗忘)的就是close操作,好在Java规范使用了优雅的Closeable接口,这样我们只需简单封装调用此接口的方法即可。

关闭操作会面临两个问题:

被关闭对象为空
对象关闭失败(或对象已关闭)IoUtil.close方法很好的解决了这两个问题。

UUID

UUID全称通用唯一识别码
import cn.hutool.core.lang.UUID;

randomUUID()

    @Test
    public void testRandomUUID(){
        System.out.println(UUID.randomUUID().toString());
        //结果生成类似:1b473b7e-1c01-4832-9507-ddcb9eb9242f 这样的字符串
    }

JSONObject

set() 设置key-value形式的值

    @Test
    public void testSet(){
        JSONObject jsonObject=new JSONObject();
        //使用JSONObject我们可以使用链式编程来设置多个值
        jsonObject.set("id",1)
                .set("name","dong")
                .set("age",18);
        System.out.println(jsonObject.toString());
        //{"name":"dong","id":1,"age":18}
    }

getJSONArray() 将JSONObject的key的值转换为JSONArray

    @Test
    public void testGetJsonArray(){
        JSONObject jsonObject=new JSONObject();
        //必须是下面这种格式json数据才能被转换为json数组
        jsonObject.set("result","[{\"name\":\"dong\",\"id\":1},{\"name\":\"sjbxsyl\",\"id\":2}]");
        //{"result":"[{\"name\":\"dong\",\"id\":1},{\"name\":\"sjbxsyl\",\"id\":2}]"}
        System.out.println(jsonObject.toString());
        //[{"name":"dong","id":1},{"name":"sjbxsyl","id":2}]
        System.out.println(jsonObject.getJSONArray("result"));
    }

containsKey() JSONObject是否包含某一个key

    @Test
    public void testContainskey(){
        JSONObject jsonObject=new JSONObject();
        jsonObject.set("id",1)
                .set("name","dong")
                .set("age",18);
        System.out.println(jsonObject.containsKey("name"));//true
    }

getStr() 获取某一个key的值

    @Test
    public void testGetStr(){
        JSONObject jsonObject=new JSONObject();
        jsonObject.set("id",1)
                .set("name","dong")
                .set("age",18);
        System.out.println(jsonObject.getStr("name"));//dong
    }

JSONArray

add()添加元素

    @Test
    public void testAdd(){
        JSONArray jsonArray=new JSONArray();
        //将json对象添加到json数组,true表示按照添加时候的顺序
        jsonArray.add(new JSONObject(true).set("name","dong").set("age","18"));
        jsonArray.add(new JSONObject(true).set("name","sjbxsyl").set("age","28"));
        jsonArray.add(new JSONObject(true).set("name","lxr").set("age","16"));
        jsonArray.add(new JSONObject(true).set("name","hkmxy").set("age","12"));
        System.out.println(jsonArray);
    }
[{"name":"dong","age":"18"},{"name":"sjbxsyl","age":"28"},{"name":"lxr","age":"16"},{"name":"hkmxy","age":"12"}]
posted @ 2021-07-28 09:17  懒鑫人  阅读(1218)  评论(1编辑  收藏  举报