Java常用工具类汇总 附示例代码

 更新时间:2021年04月09日 11:13:49   作者:GooReey  
这篇文章主要介绍了Java常用工具类汇总 附示例代码,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

一、FileUtils

private static void fileUtilsTest() {
    try {
        //读取文件内容
        String readFileToString = FileUtils.readFileToString(new File("D:\\guor\\data\\test20211022000000.txt"));
        System.out.println(readFileToString);
        //删除文件夹
        FileUtils.deleteDirectory(new File("D:\\guor1\\data1"));
        FileUtils.deleteQuietly(new File("D:\\guor\\data"));
        //清空文件夹
        FileUtils.cleanDirectory(new File("D:\\guor\\data"));
        //判断文件内容是否一致
        boolean contentEquals = FileUtils.contentEquals(new File("D:\\guor\\data\\test20211022000000.txt"), new File("D:\\guor\\data\\testNew20211021000000.txt"));
        boolean contentEquals2 = FileUtils.contentEquals(new File("D:\\guor\\data\\中文20211021100000.txt"), new File("D:\\guor\\data\\中文New20211022100000.txt"));
        System.out.println(contentEquals+","+contentEquals2);
        //拷贝特定类型的文件
        FileUtils.copyDirectory(new File("D:\\guor\\data"), new File("D:\\guor\\data2"), new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                if(pathname.getName().startsWith("test")) {
                    return true;
                }
                return false;
            }
        });
        FileUtils.moveDirectory(new File("D:\\guor\\data"), new File("D:\\guor\\data3"));
        FileUtils.moveFileToDirectory(new File("D:\\guor\\data"), new File("D:\\guor\\data3"), true);
        FileUtils.moveToDirectory(new File("D:\\guor\\data"), new File("D:\\guor\\data4"), true);
        boolean directoryContains = FileUtils.directoryContains(new File("D:\\guor\\data"), new File("D:\\guor\\data\\test20211022000000.txt"));
        System.out.println(directoryContains);
        directoryContains = FileUtils.directoryContains(new File("D:\\guor\\data"), new File("*.txt"));
        System.out.println(directoryContains);
        //获取某文件夹下特定格式文件
        File[] listFiles = new File("D:\\guor\\data").listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                return name.startsWith("test");
            }
        });
 
        System.out.println(Arrays.toString(listFiles));
        //获取系统temp文件夹路径
        File tempDirectory = FileUtils.getTempDirectory();
        System.out.println(tempDirectory);
        //获取系统用户文件夹路径
        File userDirectory = FileUtils.getUserDirectory();
        System.out.println(userDirectory);
 
        //查看是否是新建的文件夹
        SimpleDateFormat sdf =new SimpleDateFormat("yyyyMMddHHmmss" );
        Date parse = sdf.parse("20210206134900");
        boolean fileNewer = FileUtils.isFileNewer(new File("D:\\guor\\data"), parse);
        System.out.println(fileNewer);
        //更新文件修改时间,如果不存在,则新建;
        FileUtils.touch(new File("D:\\guor\\data\\test20211022000000.txt"));
        //延迟查看文件是否存在
        boolean waitFor = FileUtils.waitFor(new File("D:\\guor\\data\\testNew20211021000000.txt"), 5);
        System.out.println(waitFor);
    } catch (Exception e) {
        System.out.println(e);
    }
}
//根据文件修改时间排序
public static void test02() {
    String dir = "D:\\data";
    File[] listFiles = new File(dir).listFiles();
    List<File> asList = Arrays.asList(listFiles);
    for(File file:listFiles) {
        System.out.println(file);
    }
    Collections.sort(asList, new Comparator<File>() {
        @Override
        public int compare(File o1, File o2) {
            if(o1.lastModified()<o2.lastModified()) {
                return -1;
            }else if(o1.lastModified()>o2.lastModified()) {
                return 1;
            }else {
                return 0;
            }
        }
    });
    System.out.println("sort...");
    for(File file:listFiles) {
        System.out.println(file+","+file.lastModified());
    }
}

二、StringUtil

private static void stringUtilsTest() {
    String str = "hello world";
    //将第一个字符大写
    String capitalize = StringUtils.capitalize(str);
    System.out.println(capitalize);//Hello
    //两边空格补齐
    String center = StringUtils.center(str, 7);
    System.out.println(center);// hello
    String center = StringUtils.center(str, 7, "*");
    System.out.println(center);//*hello*
    //chomp剔除字符串最后一个是\n或\r\或\r\n
    String chomp = StringUtils.chomp(str);
    System.out.println(chomp);
    //chop剔除字符串最后一个字符(如果最后一个是\n或\r\或\r\n也剔除掉)
    String chop = StringUtils.chop(str);
    System.out.println(chop);//hello worl
    //是否包含任意字符
    boolean containsAny = StringUtils.containsAny(str, "W");
    System.out.println(containsAny);
    //是否包含任意字符,忽略大小写
    containsAny = StringUtils.containsIgnoreCase(str, "W");
    System.out.println(containsAny);
 
    //有意思
    int indexOfAnyBut = StringUtils.indexOfAnyBut(str, "hello orld");
    System.out.println(indexOfAnyBut);
 
    //两个字符串从第几位开始不同
    int indexOfDifference = StringUtils.indexOfDifference(str, str);
    System.out.println(indexOfDifference);
    indexOfDifference = StringUtils.indexOfDifference(str, str+"zs");
    System.out.println(indexOfDifference);
    indexOfDifference = StringUtils.indexOfDifference(str, "he llo");
    System.out.println(indexOfDifference);
 
    //判断是否是正整数
    boolean isNumeric = StringUtils.isNumeric(str);
    System.out.println(isNumeric);//false
    isNumeric = StringUtils.isNumeric("1234dd");
    System.out.println("1234dd:"+isNumeric);//false
    isNumeric = StringUtils.isNumeric("1234 ");
    System.out.println("1234 :"+isNumeric);//false
    isNumeric = StringUtils.isNumeric("1.234");
    System.out.println("1.234:"+isNumeric);//false
    isNumeric = StringUtils.isNumeric("1234");
    System.out.println("1234:" + isNumeric);//true
    isNumeric = StringUtils.isNumeric("-1234");
    System.out.println("-1234:" + isNumeric);//false
    //判断是否是正整数或空格
    boolean isNumeric = StringUtils.isNumericSpace(str);
 
    //将数组变为字符串,并添加字符进行分割
    Object[] array = new Object[] {"zs",18,"男",666,777};
    String join = StringUtils.join(array);
    System.out.println(Arrays.toString(array));
    join = StringUtils.join(array, "*");
    System.out.println(join);
    Object[] array = new Object[] {"zs",18,"男",666,777};
    String join = StringUtils.join(array, ";", 2, 5);
    System.out.println(join);
 
    String remove = StringUtils.remove(str, "hello");
    System.out.println(remove);// world
    String repeat = StringUtils.repeat(str, 3);
    System.out.println(repeat);//hello worldhello worldhello world
    repeat = StringUtils.repeat(str, ",", 3);
    System.out.println(repeat);//hello world,hello world,hello world
 
    //分别替换
    String[] list =  new String[] {"hello", "girl"};
    String[] replacementList =  new String[] {"say", "woman"};
    String str2 = "hello world,hello boy,hello girl.";
    String replaceEach = StringUtils.replaceEach(str2, list, replacementList);
    System.out.println(replaceEach);//say world,say boy,say woman.
 
    //只替换第一个匹配的字符串
    String replaceOnce = StringUtils.replaceOnce("hello world,hello boy,hello girl.", "hello", "say");
    System.out.println(replaceOnce);//say world,hello boy,hello girl.
 
    //截取某字符后面的部分
    String substringAfterLast = StringUtils.substringAfterLast("hello world,hello boy,hello girl.", " ");
    System.out.println(substringAfterLast);//girl.
 
    String substringBeforeLast = StringUtils.substringBeforeLast("hello world,hello boy,hello girl.", " ");
    System.out.println(substringBeforeLast);//hello world,hello boy,hello
}

三、CollectionUtils

private static void collectionUtilsTest() {
    List<String> list = new ArrayList<String>();
    list.add("zhangsan");
    list.add("dalian");
    list.add("gateway");
    list.add("gateway");
    list.add("28");
    list.add("35");
    //查找第一个符合条件的元素
    Object find = CollectionUtils.find(list, new Predicate() {
        @Override
        public boolean evaluate(Object arg0) {
            if(StringUtils.isNumeric(arg0.toString())) {
                return false;
            }
            return true;
        }
    });
 
    //排除不符合条件的元素
    Collection select = CollectionUtils.select(list, new Predicate() {
        @Override
        public boolean evaluate(Object arg0) {
            if(StringUtils.isNumeric(arg0.toString())) {
                return false;
            }
            return true;
        }
    });
    System.out.println(list);//[zhangsan, dalian, 28]
    System.out.println(find);//zhangsan
    System.out.println(select);//[zhangsan, dalian]
 
 
    List<String> list2 = new ArrayList<String>();
    list2.add("zhangsan");
    list2.add("dalian2");
    list2.add("282");
    //查看两个集合中是否有相同的元素
    boolean containsAny = CollectionUtils.containsAny(list, list2);
    System.out.println(containsAny);//true
 
    //查找集合中某元素的个数
    int countMatches = CollectionUtils.countMatches(list, new Predicate() {
        @Override
        public boolean evaluate(Object arg0) {
            if(StringUtils.isNumeric(arg0.toString())) {
                return true;
            }
            return false;
        }
    });
    System.out.println(countMatches);
 
    //查找集合中是否存在某元素
    boolean exists = CollectionUtils.exists(list, new Predicate() {
        @Override
        public boolean evaluate(Object arg0) {
            if(StringUtils.isNumeric(arg0.toString())) {
                return true;
            }
            return false;
        }
    });
 
    System.out.println(exists);
 
    //删除集合中的某些元素
    System.out.println(list);//[zhangsan, dalian, 打法, 28, 35]
    CollectionUtils.filter(list, new Predicate() {
        @Override
        public boolean evaluate(Object arg0) {
            if(StringUtils.isNumeric(arg0.toString())) {
                return false;
            }
            return true;
        }
    });
 
    System.out.println(list);//[zhangsan, dalian, 打法]
 
    //查找集合中符合条件的第一个元素
    Object find = CollectionUtils.find(list, new Predicate() {
        @Override
        public boolean evaluate(Object arg0) {
            if(StringUtils.isNumeric(arg0.toString())) {
                return false;
            }
            return true;
        }
    });
    System.out.println(find);//zhangsan
 
    //闭包回调函数
    System.out.println(list);
    CollectionUtils.forAllDo(list, new Closure() {
        @Override
        public void execute(Object arg0) {
            if(StringUtils.isNumeric(arg0.toString())) {
                work(arg0);
            }
        }
    });
    System.out.println(list);
 
    //查找集合中元素的个数
    System.out.println(list);//[zhangsan, dalian, gateway, gateway, 28, 35]
    Map cardinalityMap = CollectionUtils.getCardinalityMap(list);
    System.out.println(cardinalityMap);//{35=1, 28=1, zhangsan=1, dalian=1, gateway=2}
 
    //查找两个集合中的相同元素
    List<String> list2 = new ArrayList<String>();
    list2.add("lisi");
    list2.add("beijing");
    list2.add("gateway");
    list.add("19");
    Collection intersection = CollectionUtils.intersection(list, list2);
    System.out.println(intersection);
 
    //获取两个List<Map<String, Object>>中相同的部分,可以用于对比两个库中的相同表数据是否相等
    List<Map<String, Object>> list3 = new ArrayList<Map<String,Object>>();
    List<Map<String, Object>> list4 = new ArrayList<Map<String,Object>>();
    Map<String, Object> map1 = new HashMap<String, Object>();
    map1.put("name", "zhangsan");
    map1.put("age", 18);
    map1.put("address", "dalian");
    Map<String, Object> map2 = new HashMap<String, Object>();
    map2.put("name", "张三");
    map2.put("age", "十八");
    map2.put("address", "大连");
    list3.add(map1);
    list3.add(map2);
 
    Map<String, Object> map3 = new HashMap<String, Object>();
    map3.put("name", "李四");
    map3.put("age", "十八");
    map3.put("address", "大连");
    list4.add(map2);
    list4.add(map1);
    list3.add(map3);
    System.out.println(list3);
    System.out.println(list4);
    Collection intersection = CollectionUtils.intersection(list3, list4);
    System.out.println(intersection);//[{address=dalian, name=zhangsan, age=18}]
 
    //判断两个集合是否相同
    boolean equalCollection = CollectionUtils.isEqualCollection(list3, list4);
    System.out.println(equalCollection);
 
    判断param2是否包含param1,且不能完全相同
    System.out.println(list3);//[{address=dalian, name=zhangsan, age=18}, {address=大连, name=张三, age=十八}, {address=大连, name=李四, age=十八}]
    System.out.println(list4);//[{address=大连, name=张三, age=十八}, {address=dalian, name=zhangsan, age=18}]
    boolean properSubCollection = CollectionUtils.isProperSubCollection(list4, list3);
    System.out.println(properSubCollection);//true
 
    //断定某集合是否含有某元素,如果包含则抛异常(我觉得应该少用为妙)
    System.out.println(list);//[zhangsan, dalian, gateway, gateway, 28, 35]
    Collection predicatedCollection = CollectionUtils.predicatedCollection(list, new Predicate() {
        @Override
        public boolean evaluate(Object object) {
            if(StringUtils.isNumeric(object.toString())) {
                return false;
            }
            return true;
        }
    });
    System.out.println(predicatedCollection);//Exception in thread "main" java.lang.IllegalArgumentException: Cannot add Object '28' - Predicate rejected it
    List<String> list2 = new ArrayList<String>();
    list2.add("gateway");
    System.out.println(list);
    System.out.println(list2);
    //删除list1中的list2
    Collection removeAll = CollectionUtils.removeAll(list, list2);
    System.out.println(removeAll);
 
    //反转数组
    String[] array = new String[] {"zs","ls","ww"};
    System.out.println(StringUtils.join(array, ","));//zs,ls,ww
    CollectionUtils.reverseArray(array);
    System.out.println(StringUtils.join(array, ","));//ww,ls,zs
 
    删除list1中的list2
    List<String> list2 = new ArrayList<String>();
    list2.add("zhangsan");
    list2.add("dalian");
    Collection subtract = CollectionUtils.subtract(list, list2);
    System.out.println(subtract);
 
    //更改集合中的特定值
    Collection collect = CollectionUtils.collect(list, new Transformer() {
        @Override
        public Object transform(Object arg0) {
            if(StringUtils.isNumeric(arg0.toString())) {
                return 15;
            }
            return arg0;
        }
    });
    System.out.println(list);//[zhangsan, dalian, 28, 35]
    System.out.println(collect);//[zhangsan, dalian, 15, 15]
 
    //更改集合中的特定值,改变集合本身
    System.out.println(list);//[zhangsan, dalian, gateway, gateway, 28, 35]
    CollectionUtils.transform(list, new Transformer() {
 
        @Override
        public Object transform(Object input) {
            if(StringUtils.isNumeric(input.toString())) {
                return 15;
            }
            return input;
        }
    });
    System.out.println(list);//[zhangsan, dalian, gateway, gateway, 15, 15]
    List<String> list2 = new ArrayList<String>();
    list2.add("docker");
    list2.add("zhangsan");
    System.out.println(list);
    System.out.println(list2);
    //将list和list2中的元素合并,但去除list2中的重复元素
    Collection union = CollectionUtils.union(list, list2);
    System.out.println(union);
}
private static void work(Object obj){
    System.out.println("闭包回调函数:我是数字,"+obj);
}

四、ArrayUtils

private static void arrayUtilsTest() {
    String[] array =new String[] {"zs", "ls"};
 
    //增加元素
    Object[] add = ArrayUtils.add(array, "ww");
    System.out.println(StringUtils.join(add, ","));//zs,ls,ww
 
    //合并数组
    String[] array2 =new String[] {"ww", "ss"};
    Object[] addAll = ArrayUtils.addAll(array1, array2);
    System.out.println(StringUtils.join(addAll, ","));//zs,ls,ww,ss
 
    //克隆数组
    Object[] clone = ArrayUtils.clone(array);
    System.out.println(StringUtils.join(clone, ","));//zs,ls
 
 
    boolean contains = ArrayUtils.contains(array, "ww");
    boolean contains1 = ArrayUtils.contains(array, "zs");
    System.out.println(contains+","+contains1);//false,true
}

到此这篇关于Java常用工具类汇总 附示例代码的文章就介绍到这了,更多相关Java常用工具类内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Intellij IDEA 阅读源码的 4 个绝技(必看)

    Intellij IDEA 阅读源码的 4 个绝技(必看)

    今天小编给大家分享Intellij IDEA 阅读源码的 4 个绝技,熟练的运用 IDEA 中各个小技巧,让阅读跟踪源码变得更轻松,本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧
    2020-04-04
  • Logger.getLogger()与LogFactory.getLog()的区别详解

    Logger.getLogger()与LogFactory.getLog()的区别详解

    LogFactory来自common-logging包。如果用LogFactory.getLog,你可以用任何实现了通用日志接口的日志记录器替换log4j,而程序不受影响
    2013-09-09
  • 一文搞懂spring boot本地事务@Transactional参数

    一文搞懂spring boot本地事务@Transactional参数

    这篇文章主要介绍了spring boot本地事务@Transactional参数详解,本文通过示例代码图文相结合给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-10-10
  • Java开发中常用的 Websocket 技术参考

    Java开发中常用的 Websocket 技术参考

    WebSocket 使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据,当然也支持客户端发送数据到服务端。
    2020-09-09
  • 基于Jmeter生成测试报告过程图解

    基于Jmeter生成测试报告过程图解

    这篇文章主要介绍了基于Jmeter生成测试报告过程图解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-08-08
  • 基于Restful接口调用方法总结(超详细)

    基于Restful接口调用方法总结(超详细)

    下面小编就为大家带来一篇基于Restful接口调用方法总结(超详细)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-08-08
  • 新手了解java基础知识(二)

    新手了解java基础知识(二)

    这篇文章主要介绍了Java基础知识,本文介绍了Java语言相关的基础知识、历史介绍、主要应用方向等内容,需要的朋友可以参考下,希望对你有所帮助
    2021-07-07
  • 利用json2POJO with Lombok 插件自动生成java类的操作

    利用json2POJO with Lombok 插件自动生成java类的操作

    这篇文章主要介绍了利用json2POJO with Lombok 插件自动生成java类的操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-12-12
  • java 转发和重定向区别及实例代码

    java 转发和重定向区别及实例代码

    这篇文章主要介绍了java 转发和重定向区别及实例代码的相关资料,需要的朋友可以参考下
    2016-11-11
  • maven解决包冲突方法详解

    maven解决包冲突方法详解

    这篇文章主要介绍了maven解决包冲突方法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-10-10

最新评论