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常用工具類內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀:

    None Found