一些Java工具类

一、BeanUtil.Class

package com.supcon.mare.tankinfo.util;

import com.alibaba.excel.util.CollectionUtils;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;

/**
 * @author: zhaoxu
 * @description:
 */
public class BeanUtil {
    /**
     * 通过方法名动态执行某个方法
     *
     * @param object
     * @param methodName
     * @param parameters
     * @return
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     * @throws NoSuchMethodException
     */
    public static Object executeMethod(Object object, String methodName, Object... parameters) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
        Class<?> clazz = object.getClass();
        ArrayList<Class<?>> paramTypeList = new ArrayList<>();
        for (Object paramType : parameters) {
            paramTypeList.add(paramType.getClass());
        }
        Class<?>[] classArray = new Class[paramTypeList.size()];
        Method method = clazz.getMethod(methodName, paramTypeList.toArray(classArray));
        Object invoke = method.invoke(object, parameters);
        return invoke;
    }

    /**
     * 获取所有属性值
     *
     * @return
     * @throws IllegalAccessException
     */
    public static Map<String, Object> getFieldsValue(Object object) throws IllegalAccessException {
        Class<?> clazz = object.getClass();
        Map<String, Object> fieldValuesMap = new HashMap<>(16);
        Field[] fields = clazz.getDeclaredFields();

        for (Field field : fields) {
            field.setAccessible(true);
            Object fieldValue = field.get(object);
            fieldValuesMap.put(field.getName(), fieldValue);
        }
        return fieldValuesMap;
    }

    /**
     * 设置属性值
     *
     * @param property
     * @param value
     */
    public static Boolean setValue(Object object, String property, Object value) {
        Class<?> clazz = object.getClass();
        try {
            Field declaredField = clazz.getDeclaredField(property);
            declaredField.setAccessible(true);
            declaredField.set(object, value);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
        return true;
    }

    /**
     * 获取对象所有属性及对应的类别
     *
     * @param object
     * @return
     * @throws IllegalAccessException
     */
    public static Map<String, Class<?>> getFields(Object object) throws IllegalAccessException {
        Class<?> clazz = object.getClass();
        Map<String, Class<?>> attrMap = new HashMap<>(16);
        if (clazz != null) {
            Iterator<String> iterator = getValues(object).keySet().iterator();

            while (iterator.hasNext()) {
                attrMap.put(iterator.next(), Object.class);
            }
        }
        return attrMap;
    }

    /**
     * 获取所有属性值
     *
     * @return
     * @throws IllegalAccessException
     */
    public static Map<String, Object> getValues(Object object) throws IllegalAccessException {
        Map<String, Object> fieldValuesMap = new HashMap<>(16);
        Class<?> clazz = object.getClass();
        if (clazz != null) {
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                Object fieldValue = field.get(object);
                fieldValuesMap.put(field.getName(), fieldValue);
            }
            return fieldValuesMap;
        }
        return fieldValuesMap;
    }

    /**
     * 获取拥有指定注解的字段
     *
     * @param objectClass
     * @param annoClass
     * @return
     */
    public static List<Field> getTargetAnnoation(Class<?> objectClass, Class<? extends Annotation> annoClass) {
        List<Field> fields = new ArrayList<>();
        Field[] declaredFields = objectClass.getDeclaredFields();

        for (Field field : declaredFields) {
            field.setAccessible(true);
            if (!field.isAnnotationPresent(annoClass)) {
                continue;
            } else {
                fields.add(field);
            }
        }

        if (!CollectionUtils.isEmpty(fields)) {
            return fields;
        } else {
            return null;
        }
    }
}

二、ListUtil.Class

package com.supcon.mare.tankinfo.util;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: zhaoxu
 * @description:
 */
public class ListUtil {
    /**
     * 列表转为字符串
     *
     * @param data  数据
     * @param split 分隔符
     * @return  字符串
     */
    public static String joinList(List data, String split) {
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < data.size(); i++) {
            Object item = data.get(i);
            //跳过null值
            if (item != null) {
                result.append(item.toString());
                //如果不是最后一个
                if (i + 1 < data.size()) {
                    result.append(split);
                }
            }
        }
        return result.toString();
    }

    /**
     * 字符串转为list
     *
     * @param data  数据
     * @param split 切割符号
     * @return  列表
     */
    public static List<String> splitIntoList(String data, String split) {
        //为空
        if (data == null) {
            return null;
        }
        String[] splitArray = data.split(split);
        if (splitArray.length > 0) {
            List<String> resultList = new ArrayList<>();
            for (String item : splitArray) {
                //自动跳过空值
                if (item != null && !"".equals(item)) {
                    resultList.add(item);
                }
            }
            return resultList;
        } else {
            return null;
        }
    }

    /**
     * 分页
     *
     * @param data  数据
     * @param current  页数
     * @param pageSize 每页条数
     * @return  map
     */
    public static <E> Map<String, Object> toPage(List<E> data, int current, int pageSize) {
        //判空
        if (data == null || data.size() <= 0) {
            return null;
        }
        Map<String, Object> destMap = new HashMap<>(4);
        List<E> pageList = data.stream()
                .skip((current - 1) * pageSize)
                .limit(pageSize)
                .collect(Collectors.toList());
        //分页需要的参数
        destMap.put("list", pageList);
        destMap.put("current", current);
        destMap.put("pageSize", pageSize);
        destMap.put("total", data.size());
        return destMap;
    }

    /**
     * 查找在列表1中列表2中没有的元素
     * @param list1 列表1
     * @param list2 列表2
     * @param <E>   泛型
     * @return  差异列表
     */
    public static <E> List<E> getListDiff(List<E> list1, List<E> list2) {
        if (list1 == null || list1.isEmpty()) {
            return list2 == null || list2.isEmpty() ? new ArrayList<>() : list2;
        }

        if (list2 == null || list2.isEmpty()) {
            return list1 == null || list1.isEmpty() ? new ArrayList<>() : list1;
        }

        Set<E> diffSet = new HashSet<>(list1);
        Set<E> setOfCommonElements = new HashSet<>(list2);

        //先把列表2全部加进来
        diffSet.addAll(list2);
        //调用方法保留共有元素
        setOfCommonElements.retainAll(list1);

        //移除共有的
        diffSet.removeAll(setOfCommonElements);

        return new ArrayList<>(diffSet);
    }
}

三、MapUtil.Class

package com.supcon.mare.oms.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;

/**
 * @author ZhaoXu
 * @date 2021/11/12 14:24
 */
public class MapUtil {
    @FunctionalInterface
    /**
     * 内部接口
     */
    public interface Comparetor<T> {
        /**
         * 比较函数
         *
         * @param o1
         * @param o2
         * @return
         */
        Boolean compare(T o1, T o2);
    }
    /**
     * 过滤map
     *
     * @param map
     * @param predicate
     * @return
     */
    public static <T> Map<String, T> filter(Map<String, T> map, Predicate<Map.Entry<String, T>> predicate) {
        Map<String, T> newMap = new HashMap<>(8);
        for (Map.Entry<String, T> entry : map.entrySet()) {
            //按照自定义规则过滤
            String key = entry.getKey();
            T value = entry.getValue();
            //调用test方法
            if (predicate.test(entry)) {
                newMap.put(key, value);
            }
        }
        return newMap;
    }

    /**
     * map排序
     *
     * @param map
     * @param comparator lambda自定义比较条件
     * @param <T>
     * @return
     */
    public static <T> List<Map.Entry<String, T>> sort(Map<String, T> map, Comparetor<Map.Entry<String, T>> comparator) {
        //先存到列表,好做处理
        List<Map.Entry<String, T>> resultList = new ArrayList<>();
        resultList.addAll(map.entrySet());
        quickSort(resultList, 0, map.size() - 1, comparator);
        return resultList;
    }

    /**
     * 快排
     *
     * @param a
     * @param start
     * @param end
     */
    public static <L> void quickSort(List<L> a, int start, int end, Comparetor<L> comparator) {
        if (a.size() < 0) {
            return;
        }
        if (start >= end) {
            return;
        }
        int left = start;
        int right = end;
        L temp = a.get(left);
        while (left < right) {
            //从右面找
            while (left < right && comparator.compare(a.get(right), temp)) {
                right--;
            }
            //从左面找
            a.set(left, a.get(right));
            while (left < right && !comparator.compare(a.get(left), temp)) {
                left++;
            }
            //把坑填上
            a.set(right, a.get(left));
        }
        a.set(left, temp);
        quickSort(a, start, left - 1, comparator);
        quickSort(a, left + 1, end, comparator);
    }

    /**
     * 按照正序排序
     *
     * @param entry1
     * @param entry2
     * @param <T>
     * @return
     */
    public static <T> Boolean ascByValue(Map.Entry<String, T> entry1, Map.Entry<String, T> entry2) {
        return entry1.getValue().toString().compareTo(entry2.getValue().toString()) >= 0;
    }

    /**
     * 按照倒序排序
     *
     * @param entry1
     * @param entry2
     * @param <T>
     * @return
     */
    public static <T> Boolean descByValue(Map.Entry<String, T> entry1, Map.Entry<String, T> entry2) {
        return entry1.getValue().toString().compareTo(entry2.getValue().toString()) <= 0;
    }

    /**
     * 按照正序排序
     *
     * @param entry1
     * @param entry2
     * @param <T>
     * @return
     */
    public static <T> Boolean ascByKey(Map.Entry<String, T> entry1, Map.Entry<String, T> entry2) {
        return entry1.getKey().compareTo(entry2.getKey()) >= 0;
    }

    /**
     * 按照倒序排序
     *
     * @param entry1
     * @param entry2
     * @param <T>
     * @return
     */
    public static <T> Boolean descByKey(Map.Entry<String, T> entry1, Map.Entry<String, T> entry2) {
        return entry1.getKey().compareTo(entry2.getKey()) <= 0;
    }
}

四、ChineseHelper.Class

pom文件:

<dependency>
            <groupId>com.belerweb</groupId>
            <artifactId>pinyin4j</artifactId>
            <version>2.5.1</version>
        </dependency>
package com.supcon.mare.tankinfo.util;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 一些中文的操作
 */
public final class ChineseHelper {

    public static final Pattern PATTERN_CHINESE_BY_REG =Pattern.compile("[\\u4E00-\\u9FBF]+");
    public static final Pattern PATTERN_CHINESE =Pattern.compile("[\u4E00-\u9FA5]+");
    public static final Pattern PATTERN_MESSY_CODE =Pattern.compile("\\s*|\t*|\r*|\n*");

    /**
     * 将字符串中的中文转化为拼音,其他字符不变
     *
     * @param inputString
     * @return
     */
    public  static String getPingYin(String inputString) {
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        format.setVCharType(HanyuPinyinVCharType.WITH_V);

        char[] input = inputString.trim().toCharArray();
        String output = "";

        try {
            for (int i = 0; i < input.length; i++) {
                if (java.lang.Character.toString(input[i]).matches("[\\u4E00-\\u9FA5]+")) {
                    String[] temp = PinyinHelper.toHanyuPinyinStringArray(input[i], format);
                    output += temp[0];
                } else{
                    output += java.lang.Character.toString(input[i]);
                }

            }
        } catch (BadHanyuPinyinOutputFormatCombination e) {
            e.printStackTrace();
        }
        return output;
    }

    /**
     * 获取汉字串拼音首字母,英文字符不变
     *
     * @param chinese 汉字串
     * @return 汉语拼音首字母
     */
    public  static String getFirstSpell(String chinese) {
        StringBuilder pybf = new StringBuilder();
        char[] arr = chinese.toCharArray();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] > 128) {
                try {
                    String[] temp = PinyinHelper.toHanyuPinyinStringArray(arr[i], defaultFormat);
                    if (temp != null) {
                        pybf.append(temp[0].charAt(0));
                    }
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            } else {
                pybf.append(arr[i]);
            }
        }
        return pybf.toString().replaceAll("\\W", "").trim();
    }

    /**
     * 获取汉字串拼音,英文字符不变
     *
     * @param chinese 汉字串
     * @return 汉语拼音
     */
    public  static String getFullSpell(String chinese) {
        StringBuffer pybf = new StringBuffer();
        char[] arr = chinese.toCharArray();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] > 128) {
                try {
                    pybf.append(PinyinHelper.toHanyuPinyinStringArray(arr[i], defaultFormat)[0]);
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            } else {
                pybf.append(arr[i]);
            }
        }
        return pybf.toString();
    }


    /**
     * 只能判断部分CJK字符(CJK统一汉字)
     * @param str
     * @return
     */
    public  static boolean isChineseByReg(String str) {
        if (str == null) {
            return false;
        }
        return PATTERN_CHINESE_BY_REG.matcher(str.trim()).find();
    }

    // 只能判断部分CJK字符(CJK统一汉字)
    public  static boolean isChineseByName(String str) {
        if (str == null) {
            return false;
        }
        // 大小写不同:\\p 表示包含,\\P 表示不包含
        // \\p{Cn} 的意思为 Unicode 中未被定义字符的编码,\\P{Cn} 就表示 Unicode中已经被定义字符的编码
        String reg = "\\p{InCJK Unified Ideographs}&&\\P{Cn}";
        Pattern pattern = Pattern.compile(reg);
        return pattern.matcher(str.trim()).find();
    }


    /**
     * 完整的判断中文汉字和符号
     * @param strName
     * @return
     */
    public  static boolean isChinese(String strName) {
        char[] ch = strName.toCharArray();
        for (int i = 0; i < ch.length; i++) {
            char c = ch[i];
            if (isChinese(c)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断是否是中文
     *
     * @param c
     * @return
     */
    public  static boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
            return true;
        }
        return false;
    }

    /**
     * 获取一个字符串中中文字符的个数
     */
    public  static int chineseLength(String str) {
        Matcher m = PATTERN_CHINESE.matcher(str);
        int i = 0;
        while (m.find()) {
            String temp = m.group(0);
            i += temp.length();
        }
        return i;
    }

    /**
     * 判断是否是乱码
     *
     * @param strName
     * @return
     */
    public  static float isMessyCode(String strName) {
        Matcher m = PATTERN_MESSY_CODE.matcher(strName);
        String after = m.replaceAll("");
        String temp = after.replaceAll("\\p{P}", "");
        char[] ch = temp.trim().toCharArray();
        float chLength = 0;
        float count = 0;
        for (char c : ch){
            if (!Character.isLetterOrDigit(c)) {
                if (!isChinese(c)) {
                    count = count + 1;
                }
                chLength++;
            }
        }

        return count / chLength;
    }

    /**
     *  18位标准身份证号
     * 方法用途:15位身份证转化为18位标准证件号
     */
    public static String transIdCard15to18(String IdCardNO){
        String cardNo=null;
        if(null!=IdCardNO&&IdCardNO.trim().length()==15){
            IdCardNO=IdCardNO.trim();
            StringBuilder sb=new StringBuilder(IdCardNO);
            sb.insert(6, "19");
            sb.append(transCardLastNo(sb.toString()));
            cardNo=sb.toString();
        }
        return cardNo;
    }

    /**
     * 15位补全身份证号码
     * @param newCardId
     * @return
     */
    private static String transCardLastNo(String newCardId){
        char[] ch=newCardId.toCharArray();
        int m=0;
        int [] co={7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2};
        char [] verCode=new char[]{'1','0','X','9','8','7','6','5','4','3','2'};
        for (int i = 0; i < newCardId.length(); i++) {
            m+=(ch[i]-'0')*co[i];
        }
        int residue=m%11;
        return String.valueOf(verCode[residue]);

    }
}

五、FileUtil.class

package com.supcon.mare.tankinfo.util;

import java.io.*;
import java.math.BigInteger;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public final class FileUtil {
    /**
     * Buffer的大小
     */
    private static Integer BUFFER_SIZE = 1024 * 1024 * 10;

    public static MessageDigest MD5 = null;

    static {
        try {
            MD5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException ne) {
            ne.printStackTrace();
        }
    }

    /**
     * 获取文件的md5
     *
     * @param file
     * @return
     */
    public static String fileMD5(File file) {
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(file);
            byte[] buffer = new byte[8192];
            int length;
            while ((length = fileInputStream.read(buffer)) != -1) {
                MD5.update(buffer, 0, length);
            }
            return new BigInteger(1, MD5.digest()).toString(16);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (fileInputStream != null) {
                    fileInputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取文件的行数
     *
     * @param file 统计的文件
     * @return 文件行数
     */
    public final static int countLines(File file) {
        try (LineNumberReader rf = new LineNumberReader(new FileReader(file))) {
            long fileLength = file.length();
            rf.skip(fileLength);
            return rf.getLineNumber();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 以列表的方式获取文件的所有行
     *
     * @param file 需要出来的文件
     * @return 包含所有行的list
     */
    public final static List<String> lines(File file) {
        List<String> list = new ArrayList<>();
        try (
                BufferedReader reader = new BufferedReader(new FileReader(file))
        ) {
            String line;
            while ((line = reader.readLine()) != null) {
                list.add(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 以列表的方式获取文件的所有行
     *
     * @param file     需要处理的文件
     * @param encoding 指定读取文件的编码
     * @return 包含所有行的list
     */
    public final static List<String> lines(File file, String encoding) {
        List<String> list = new ArrayList<>();
        try (
                BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding))
        ) {
            String line;
            while ((line = reader.readLine()) != null) {
                list.add(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 以列表的方式获取文件的指定的行数数据
     *
     * @param file  处理的文件
     * @param lines 需要读取的行数
     * @return 包含制定行的list
     */
    public final static List<String> lines(File file, int lines) {
        List<String> list = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            String line;
            while ((line = reader.readLine()) != null) {
                list.add(line);
                if (list.size() == lines) {
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 以列表的方式获取文件的指定的行数数据
     *
     * @param file     需要处理的函数
     * @param lines    需要处理的行还俗
     * @param encoding 指定读取文件的编码
     * @return 包含制定行的list
     */
    public final static List<String> lines(File file, int lines, String encoding) {
        List<String> list = new ArrayList<>();
        try (
                BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding))
        ) {
            String line;
            while ((line = reader.readLine()) != null) {
                list.add(line);
                if (list.size() == lines) {
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 在文件末尾追加一行
     *
     * @param file     需要处理的文件
     * @param str      添加的字符串
     * @param encoding 指定写入的编码
     * @return 是否成功
     */
    public final static boolean appendLine(File file, String str, String encoding) {
        String lineSeparator = System.getProperty("line.separator", "\n");
        try (
                RandomAccessFile randomFile = new RandomAccessFile(file, "rw")
        ) {
            long fileLength = randomFile.length();
            randomFile.seek(fileLength);
            randomFile.write((lineSeparator + str).getBytes(encoding));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 将字符串写入到文件中
     */
    public final static boolean write(File file, String str) {
        try (
                RandomAccessFile randomFile = new RandomAccessFile(file, "rw")
        ) {
            randomFile.writeBytes(str);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 将字符串以追加的方式写入到文件中
     */
    public final static boolean writeAppend(File file, String str) {
        try (
                RandomAccessFile randomFile = new RandomAccessFile(file, "rw")
        ) {
            long fileLength = randomFile.length();
            randomFile.seek(fileLength);
            randomFile.writeBytes(str);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 将字符串以制定的编码写入到文件中
     */
    public final static boolean write(File file, String str, String encoding) {
        try (
                RandomAccessFile randomFile = new RandomAccessFile(file, "rw")
        ) {
            randomFile.write(str.getBytes(encoding));
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 将字符串以追加的方式以制定的编码写入到文件中
     */
    public final static boolean writeAppend(File file, String str, String encoding) {
        try (
                RandomAccessFile randomFile = new RandomAccessFile(file, "rw")
        ) {
            long fileLength = randomFile.length();
            randomFile.seek(fileLength);
            randomFile.write(str.getBytes(encoding));
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 快速清空一个超大的文件
     *
     * @param file 需要处理的文件
     * @return 是否成功
     */
    public final static boolean cleanFile(File file) {
        try (
                FileWriter fw = new FileWriter(file)
        ) {
            fw.write("");
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 获取文件的Mime类型
     *
     * @param file 需要处理的文件
     * @return 返回文件的mime类型
     * @throws java.io.IOException
     */
    public final static String mimeType(String file) throws java.io.IOException {
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        return fileNameMap.getContentTypeFor(file);
    }

    /**
     * 获取文件最后的修改时间
     *
     * @param file 需要处理的文件
     * @return 返回文件的修改时间
     */
    public final static Date modifyTime(File file) {
        return new Date(file.lastModified());
    }


    /**
     * 复制文件
     *
     * @param resourcePath 源文件
     * @param targetPath   目标文件
     * @return 是否成功
     */
    public final static boolean copy(String resourcePath, String targetPath) {
        File file = new File(resourcePath);
        return copy(file, targetPath);
    }

    /**
     * 复制文件
     * 通过该方式复制文件文件越大速度越是明显
     *
     * @param file       需要处理的文件
     * @param targetFile 目标文件
     * @return 是否成功
     */
    public final static boolean copy(File file, String targetFile) {
        try (
                FileInputStream fin = new FileInputStream(file);
                FileOutputStream fout = new FileOutputStream(new File(targetFile))
        ) {
            FileChannel in = fin.getChannel();
            FileChannel out = fout.getChannel();
            //设定缓冲区
            ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE);
            while (in.read(buffer) != -1) {
                //准备写入,防止其他读取,锁住文件
                buffer.flip();
                out.write(buffer);
                //准备读取。将缓冲区清理完毕,移动文件内部指针
                buffer.clear();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }


    /**
     * 创建多级目录
     *
     * @param paths 需要创建的目录
     * @return 是否成功
     */
    public final static boolean createPaths(String paths) {
        File dir = new File(paths);
        return !dir.exists() && dir.mkdir();
    }

    /**
     * 创建文件支持多级目录
     *
     * @param filePath 需要创建的文件
     * @return 是否成功
     */
    public final static boolean createFiles(String filePath) {
        File file = new File(filePath);
        if (file.isDirectory()) {
            if (!file.exists()) {
                return file.mkdirs();
            }
        } else {
            File dir = file.getParentFile();
            if (!dir.exists()) {
                if (dir.mkdirs()) {
                    try {
                        return file.createNewFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return false;
    }

    /**
     * 删除一个文件
     *
     * @param file 需要处理的文件
     * @return 是否成功
     */
    public final static boolean deleteFile(File file) {
        return file.delete();
    }

    /**
     * 删除一个目录
     *
     * @param file 需要处理的文件
     * @return 是否成功
     */
    public final static boolean deleteDir(File file) {
        List<File> files = listFileAll(file);
        for (File f : files) {
            if (f.isDirectory()) {
                deleteDir(f);
            } else {
                deleteFile(f);
            }
        }
        return file.delete();
    }


    /**
     * 快速的删除超大的文件
     *
     * @param file 需要处理的文件
     * @return 是否成功
     */
    public final static boolean deleteBigFile(File file) {
        return cleanFile(file) && file.delete();
    }


    /**
     * 复制目录
     *
     * @param filePath   需要处理的文件
     * @param targetPath 目标文件
     */
    public final static void copyDir(String filePath, String targetPath) {
        File file = new File(filePath);
        copyDir(file, targetPath);
    }

    /**
     * 复制目录
     *
     * @param filePath   需要处理的文件
     * @param targetPath 目标文件
     */
    public final static void copyDir(File filePath, String targetPath) {
        File targetFile = new File(targetPath);
        if (!targetFile.exists()) {
            createPaths(targetPath);
        }
        File[] files = filePath.listFiles();
        for (File file : files) {
            String path = file.getName();
            if (file.isDirectory()) {
                copyDir(file, targetPath + "/" + path);
            } else {
                copy(file, targetPath + "/" + path);
            }
        }
    }

    /**
     * 罗列指定路径下的全部文件
     *
     * @param path 需要处理的文件
     * @return 包含所有文件的的list
     */
    public final static List<File> listFile(String path) {
        File file = new File(path);
        return listFile(file);
    }

    /**
     * 罗列指定路径下的全部文件
     *
     * @param path  需要处理的文件
     * @param child 是否罗列子文件
     * @return 包含所有文件的的list
     */
    public final static List<File> listFile(String path, boolean child) {
        return listFile(new File(path), child);
    }


    /**
     * 罗列指定路径下的全部文件
     *
     * @param path 需要处理的文件
     * @return 返回文件列表
     */
    public final static List<File> listFile(File path) {
        List<File> list = new ArrayList<>();
        File[] files = path.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                list.addAll(listFile(file));
            } else {
                list.add(file);
            }
        }
        return list;
    }

    /**
     * 罗列指定路径下的全部文件
     *
     * @param path  指定的路径
     * @param child 是否罗列子目录
     * @return
     */
    public final static List<File> listFile(File path, boolean child) {
        List<File> list = new ArrayList<>();
        File[] files = path.listFiles();
        for (File file : files) {
            if (child && file.isDirectory()) {
                list.addAll(listFile(file));
            } else {
                list.add(file);
            }
        }
        return list;
    }

    /**
     * 罗列指定路径下的全部文件包括文件夹
     *
     * @param path 需要处理的文件
     * @return 返回文件列表
     */
    public final static List<File> listFileAll(File path) {
        List<File> list = new ArrayList<>();
        File[] files = path.listFiles();
        for (File file : files) {
            list.add(file);
            if (file.isDirectory()) {
                list.addAll(listFileAll(file));
            }
        }
        return list;
    }

    /**
     * 罗列指定路径下的全部文件包括文件夹
     *
     * @param path   需要处理的文件
     * @param filter 处理文件的filter
     * @return 返回文件列表
     */
    public final static List<File> listFileFilter(File path, FilenameFilter filter) {
        List<File> list = new ArrayList<>();
        File[] files = path.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                list.addAll(listFileFilter(file, filter));
            } else {
                if (filter.accept(file.getParentFile(), file.getName())) {
                    list.add(file);
                }
            }
        }
        return list;
    }

    /**
     * 获取指定目录下的特点文件,通过后缀名过滤
     *
     * @param dirPath  需要处理的文件
     * @param postfixs 文件后缀
     * @return 返回文件列表
     */
    public final static List<File> listFileFilter(File dirPath, final String postfixs) {
        /*
        如果在当前目录中使用Filter讲只罗列当前目录下的文件不会罗列孙子目录下的文件
        FilenameFilter filefilter = new FilenameFilter() {
            public boolean accept(File dir, String name) {
                return name.endsWith(postfixs);
            }
        };
        */
        List<File> list = new ArrayList<File>();
        File[] files = dirPath.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                list.addAll(listFileFilter(file, postfixs));
            } else {
                String fileName = file.getName().toLowerCase();
                if (fileName.endsWith(postfixs.toLowerCase())) {
                    list.add(file);
                }
            }
        }
        return list;
    }

    /**
     * 在指定的目录下搜寻文个文件
     *
     * @param dirPath  搜索的目录
     * @param fileName 搜索的文件名
     * @return 返回文件列表
     */
    public final static List<File> searchFile(File dirPath, String fileName) {
        List<File> list = new ArrayList<>();
        File[] files = dirPath.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                list.addAll(searchFile(file, fileName));
            } else {
                String Name = file.getName();
                if (Name.equals(fileName)) {
                    list.add(file);
                }
            }
        }
        return list;
    }

    /**
     * 获取文件后缀名
     *
     * @param file
     * @return
     */
    public final static String suffix(File file) {
        String fileName = file.getName();
        return fileName.substring(fileName.indexOf(".") + 1);
    }
}

六、ZipUtil.Class

package com.supcon.supfusion.oms.commons.util;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

/**
 * 压缩文档相关的工具类
 * 注意因为jre中自带的java.util.zip.*包不支持中文及加密压缩,如果需要选择使用zip4j包
 *
 * @author zhaoxu
 */
public final class ZipUtil {
    /**
     * zip文件结尾
     */
    final static String ZIP_STR = ".zip";

    /**
     * 判断文件是否为一个压缩文件
     *
     * @param filePath
     * @return
     */
    public static boolean isZipFile(String filePath) {
        if (!filePath.contains(ZIP_STR)) {
            return false;
        }
        try (ZipFile zipFile = new ZipFile(filePath)) {
        } catch (IOException e) {
            return false;
        }
        return true;
    }

    /**
     * 读取压缩文件中的所有文件名
     *
     * @param path
     * @return
     * @throws IOException
     */
    public static List<String> getZipFileNames(String path) throws IOException {
        List<String> fileNamesList = new ArrayList<>();
        ZipEntry zipEntry;
        File file = new File(path);
        //判断文件是否存在
        if (file.exists()) {
            //解决包内文件存在中文时的中文乱码问题
            ZipInputStream zipInputStream = new ZipInputStream(Files.newInputStream(Paths.get(path)), Charset.forName("GBK"));
            while ((zipEntry = zipInputStream.getNextEntry()) != null) {
                //遇到文件夹就跳过
                if (!zipEntry.isDirectory()) {
                    fileNamesList.add(zipEntry.getName().substring(zipEntry.getName().lastIndexOf("\\") + 1));
                }
            }
        }
        return fileNamesList;
    }

    /**
     * 文档压缩
     *
     * @param file 需要压缩的文件或目录
     * @param dest 压缩后的文件名称
     * @throws IOException
     */
    public static void deCompress(File file, String dest) throws IOException {
        ZipFile zf = new ZipFile(dest);

        try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(dest))) {
            String dir = "";
            if (file.isDirectory()) {
                dir = file.getName();
            }
            zipFile(file, zos, dir);
        } catch (IOException e) {
            throw e;
        }
    }

    public static void zipFile(File inFile, ZipOutputStream zos, String dir) throws IOException {
        if (inFile.isDirectory()) {
            File[] files = inFile.listFiles();
            if (files == null || files.length == 0) {
                String entryName = dir + "/";
                zos.putNextEntry(new ZipEntry(entryName));
                return;
            }
            for (File file : files) {
                String entryName = dir + "/" + file.getName();
                if (file.isDirectory()) {
                    zipFile(file, zos, entryName);
                } else {
                    ZipEntry entry = new ZipEntry(entryName);
                    zos.putNextEntry(entry);
                    try (InputStream is = new FileInputStream(file)) {
                        int len = 0;
                        while ((len = is.read()) != -1) {
                            zos.write(len);
                        }
                    } catch (IOException e) {
                        throw e;
                    }
                }
            }
        } else {
            String entryName = dir + "/" + inFile.getName();
            ZipEntry entry = new ZipEntry(entryName);
            zos.putNextEntry(entry);
            try (InputStream is = new FileInputStream(inFile)) {
                int len = 0;
                while ((len = is.read()) != -1) {
                    zos.write(len);
                }
            } catch (IOException e) {
                throw e;
            }
        }

    }

    /**
     * 文档解压
     *
     * @param source 需要解压缩的文档名称
     * @param path   需要解压缩的路径
     */
    public static void unCompress(File source, String path) throws IOException {
        ZipEntry zipEntry = null;
        FileUtil.createPaths(path);
        //实例化ZipFile,每一个zip压缩文件都可以表示为一个ZipFile
        //实例化一个Zip压缩文件的ZipInputStream对象,可以利用该类的getNextEntry()方法依次拿到每一个ZipEntry对象
        try (
                ZipFile zipFile = new ZipFile(source);
                ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(source))
        ) {
            while ((zipEntry = zipInputStream.getNextEntry()) != null) {
                String fileName = zipEntry.getName();
                String filePath = path + "/" + fileName;
                if (zipEntry.isDirectory()) {
                    File temp = new File(filePath);
                    if (!temp.exists()) {
                        temp.mkdirs();
                    }
                } else {
                    File temp = new File(filePath);
                    if (!temp.getParentFile().exists()) {
                        temp.getParentFile().mkdirs();
                    }
                    try (OutputStream os = new FileOutputStream(temp);
                         //通过ZipFile的getInputStream方法拿到具体的ZipEntry的输入流
                         InputStream is = zipFile.getInputStream(zipEntry)) {
                        int len = 0;
                        while ((len = is.read()) != -1) {
                            os.write(len);
                        }
                    } catch (IOException e) {
                        throw e;
                    }
                }


            }
        } catch (IOException e) {
            throw e;
        }
    }
}


七、StringUtil.Class

package com.supcon.mare.tankinfo.util;

import com.alibaba.druid.util.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author ZhaoXu
 * @date 2021/11/12 13:20
 */
public class StringUtil {
    static Pattern numberPattern = Pattern.compile("[0-9]*");
    /**
     * time时间戳转Date
     *
     * @param time
     * @return
     */
    public static Date timeToDate(String time) {
        SimpleDateFormat sdfTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String str = sdfTime.format(Long.valueOf(time));
        try {
            Date date = sdfTime.parse(str);
            return date;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 日期字符串转String型Time
     *
     * @param date
     * @return
     */
    public static String stringToTime(String date) {
        SimpleDateFormat sdfTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date dateDate = sdfTime.parse(date);
            return String.valueOf(dateDate.getTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 利用正则表达式判断字符串是否是数字
     *
     * @param str
     * @return
     */
    public static boolean isNumeric(String str) {
        Matcher isNum = numberPattern.matcher(str);
        if (StringUtils.isEmpty(str) || !isNum.matches()) {
            return false;
        }
        return true;
    }

    /**
     * 首字母变小写
     * @param str
     * @return
     */
    public static String firstCharToLowerCase(String str) {
        char firstChar = str.charAt(0);
        if (firstChar >= 'A' && firstChar <= 'Z') {
            char[] arr = str.toCharArray();
            arr[0] += ('a' - 'A');
            return new String(arr);
        }
        return str;
    }

    /**
     * 首字母变大写
     * @param str
     * @return
     */
    public static String firstCharToUpperCase(String str) {
        char firstChar = str.charAt(0);
        if (firstChar >= 'a' && firstChar <= 'z') {
            char[] arr = str.toCharArray();
            arr[0] -= ('a' - 'A');
            return new String(arr);
        }
        return str;
    }

    /**
     * 判断是否为空
     * @param str
     * @return
     */
    public static boolean isEmpty(final String str) {
        return (str == null) || (str.length() == 0);
    }
}

八、ImageUtil.class

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author ZhaoXu
 * @date 2021/11/25 15:21
 */
public class ImageUtil {

    public static BufferedImage grayImage(BufferedImage bufferedImage) throws Exception {

        int width = bufferedImage.getWidth();
        int height = bufferedImage.getHeight();

        BufferedImage grayBufferedImage = new BufferedImage(width, height, bufferedImage.getType());
        for (int i = 0; i < bufferedImage.getWidth(); i++) {
            for (int j = 0; j < bufferedImage.getHeight(); j++) {
                final int color = bufferedImage.getRGB(i, j);
                final int r = (color >> 16) & 0xff;
                final int g = (color >> 8) & 0xff;
                final int b = color & 0xff;
                int gray = (int) (0.3 * r + 0.59 * g + 0.11 * b);
                int newPixel = colorToRGB(255, gray, gray, gray);
                grayBufferedImage.setRGB(i, j, newPixel);
            }
        }

        return grayBufferedImage;

    }

    /**
     * 颜色分量转换为RGB值
     *
     * @param alpha
     * @param red
     * @param green
     * @param blue
     * @return
     */
    private static int colorToRGB(int alpha, int red, int green, int blue) {

        int newPixel = 0;
        newPixel += alpha;
        newPixel = newPixel << 8;
        newPixel += red;
        newPixel = newPixel << 8;
        newPixel += green;
        newPixel = newPixel << 8;
        newPixel += blue;

        return newPixel;

    }

    public static BufferedImage binaryImage(BufferedImage image) throws Exception {
        int w = image.getWidth();
        int h = image.getHeight();
        float[] rgb = new float[3];
        double[][] zuobiao = new double[w][h];
        int black = new Color(0, 0, 0).getRGB();
        int white = new Color(255, 255, 255).getRGB();
        BufferedImage bi = new BufferedImage(w, h,
                BufferedImage.TYPE_BYTE_BINARY);
        ;
        for (int x = 0; x < w; x++) {
            for (int y = 0; y < h; y++) {
                int pixel = image.getRGB(x, y);
                rgb[0] = (pixel & 0xff0000) >> 16;
                rgb[1] = (pixel & 0xff00) >> 8;
                rgb[2] = (pixel & 0xff);
                float avg = (rgb[0] + rgb[1] + rgb[2]) / 3;
                zuobiao[x][y] = avg;

            }
        }
        //这里是阈值,白底黑字还是黑底白字,大多数情况下建议白底黑字,后面都以白底黑字为例
        double SW = 192;
        for (int x = 0; x < w; x++) {
            for (int y = 0; y < h; y++) {
                if (zuobiao[x][y] < SW) {
                    bi.setRGB(x, y, black);
                } else {
                    bi.setRGB(x, y, white);
                }
            }
        }


        return bi;
    }

    // 自己加周围8个灰度值再除以9,算出其相对灰度值
    public static double getGray(double[][] zuobiao, int x, int y, int w, int h) {
        double rs = zuobiao[x][y] + (x == 0 ? 255 : zuobiao[x - 1][y]) + (x == 0 || y == 0 ? 255 : zuobiao[x - 1][y - 1])
                + (x == 0 || y == h - 1 ? 255 : zuobiao[x - 1][y + 1]) + (y == 0 ? 255 : zuobiao[x][y - 1])
                + (y == h - 1 ? 255 : zuobiao[x][y + 1]) + (x == w - 1 ? 255 : zuobiao[x + 1][y])
                + (x == w - 1 || y == 0 ? 255 : zuobiao[x + 1][y - 1])
                + (x == w - 1 || y == h - 1 ? 255 : zuobiao[x + 1][y + 1]);
        return rs / 9;
    }

    /**
     * 降噪,以1个像素点为单位(实际使用中可以循环降噪,或者把单位可以扩大为多个像素点)
     *
     * @param image
     * @return
     */
    public static BufferedImage denoise(BufferedImage image) {
        int w = image.getWidth();
        int h = image.getHeight();
        int white = new Color(255, 255, 255).getRGB();

        if (isWhite(image.getRGB(1, 0)) && isWhite(image.getRGB(0, 1)) && isWhite(image.getRGB(1, 1))) {
            image.setRGB(0, 0, white);
        }
        if (isWhite(image.getRGB(w - 2, 0)) && isWhite(image.getRGB(w - 1, 1)) && isWhite(image.getRGB(w - 2, 1))) {
            image.setRGB(w - 1, 0, white);
        }
        if (isWhite(image.getRGB(0, h - 2)) && isWhite(image.getRGB(1, h - 1)) && isWhite(image.getRGB(1, h - 2))) {
            image.setRGB(0, h - 1, white);
        }
        if (isWhite(image.getRGB(w - 2, h - 1)) && isWhite(image.getRGB(w - 1, h - 2)) && isWhite(image.getRGB(w - 2, h - 2))) {
            image.setRGB(w - 1, h - 1, white);
        }

        for (int x = 1; x < w - 1; x++) {
            int y = 0;
            if (isBlack(image.getRGB(x, y))) {
                int size = 0;
                if (isWhite(image.getRGB(x - 1, y))) {
                    size++;
                }
                if (isWhite(image.getRGB(x + 1, y))) {
                    size++;
                }
                if (isWhite(image.getRGB(x, y + 1))) {
                    size++;
                }
                if (isWhite(image.getRGB(x - 1, y + 1))) {
                    size++;
                }
                if (isWhite(image.getRGB(x + 1, y + 1))) {
                    size++;
                }
                if (size >= 5) {
                    image.setRGB(x, y, white);
                }
            }
        }
        for (int x = 1; x < w - 1; x++) {
            int y = h - 1;
            if (isBlack(image.getRGB(x, y))) {
                int size = 0;
                if (isWhite(image.getRGB(x - 1, y))) {
                    size++;
                }
                if (isWhite(image.getRGB(x + 1, y))) {
                    size++;
                }
                if (isWhite(image.getRGB(x, y - 1))) {
                    size++;
                }
                if (isWhite(image.getRGB(x + 1, y - 1))) {
                    size++;
                }
                if (isWhite(image.getRGB(x - 1, y - 1))) {
                    size++;
                }
                if (size >= 5) {
                    image.setRGB(x, y, white);
                }
            }
        }

        for (int y = 1; y < h - 1; y++) {
            int x = 0;
            if (isBlack(image.getRGB(x, y))) {
                int size = 0;
                if (isWhite(image.getRGB(x + 1, y))) {
                    size++;
                }
                if (isWhite(image.getRGB(x, y + 1))) {
                    size++;
                }
                if (isWhite(image.getRGB(x, y - 1))) {
                    size++;
                }
                if (isWhite(image.getRGB(x + 1, y - 1))) {
                    size++;
                }
                if (isWhite(image.getRGB(x + 1, y + 1))) {
                    size++;
                }
                if (size >= 5) {
                    image.setRGB(x, y, white);
                }
            }
        }

        for (int y = 1; y < h - 1; y++) {
            int x = w - 1;
            if (isBlack(image.getRGB(x, y))) {
                int size = 0;
                if (isWhite(image.getRGB(x - 1, y))) {
                    size++;
                }
                if (isWhite(image.getRGB(x, y + 1))) {
                    size++;
                }
                if (isWhite(image.getRGB(x, y - 1))) {
                    size++;
                }
                //斜上下为空时,去掉此点
                if (isWhite(image.getRGB(x - 1, y + 1))) {
                    size++;
                }
                if (isWhite(image.getRGB(x - 1, y - 1))) {
                    size++;
                }
                if (size >= 5) {
                    image.setRGB(x, y, white);
                }
            }
        }

        //降噪,以1个像素点为单位
        for (int y = 1; y < h - 1; y++) {
            for (int x = 1; x < w - 1; x++) {
                if (isBlack(image.getRGB(x, y))) {
                    int size = 0;
                    //上下左右均为空时,去掉此点
                    if (isWhite(image.getRGB(x - 1, y))) {
                        size++;
                    }
                    if (isWhite(image.getRGB(x + 1, y))) {
                        size++;
                    }
                    //上下均为空时,去掉此点
                    if (isWhite(image.getRGB(x, y + 1))) {
                        size++;
                    }
                    if (isWhite(image.getRGB(x, y - 1))) {
                        size++;
                    }
                    //斜上下为空时,去掉此点
                    if (isWhite(image.getRGB(x - 1, y + 1))) {
                        size++;
                    }
                    if (isWhite(image.getRGB(x + 1, y - 1))) {
                        size++;
                    }
                    if (isWhite(image.getRGB(x + 1, y + 1))) {
                        size++;
                    }
                    if (isWhite(image.getRGB(x - 1, y - 1))) {
                        size++;
                    }
                    if (size >= 8) {
                        image.setRGB(x, y, white);
                    }
                }
            }
        }

        return image;
    }

    public static boolean isBlack(int colorInt) {
        Color color = new Color(colorInt);
        if (color.getRed() + color.getGreen() + color.getBlue() <= 300) {
            return true;
        }
        return false;
    }

    public static boolean isWhite(int colorInt) {
        Color color = new Color(colorInt);
        if (color.getRed() + color.getGreen() + color.getBlue() > 300) {
            return true;
        }
        return false;
    }

    public static int isBlack(int colorInt, int whiteThreshold) {
        final Color color = new Color(colorInt);
        if (color.getRed() + color.getGreen() + color.getBlue() <= whiteThreshold) {
            return 1;
        }
        return 0;
    }

    /**
     * 放大缩小处理
     * @param imgsrc
     * @param widthdist
     * @param heightdist
     */
    public static void reduceImg(String imgsrc, int widthdist, int heightdist) {
        try {
            File srcfile = new File(imgsrc);
            if (!srcfile.exists()) {
                return;
            }

            //载入图片文件
            Image src = javax.imageio.ImageIO.read(srcfile);
            int w0 = src.getWidth(null);    //得到源图宽
            int h0 = src.getHeight(null);   //得到源图长

            BufferedImage tag = new BufferedImage((int) widthdist, (int) heightdist, BufferedImage.TYPE_INT_RGB);

            //保存文件
            //绘制缩小后的图
            tag.getGraphics().drawImage(src.getScaledInstance(widthdist, heightdist, Image.SCALE_SMOOTH), 0, 0, null);
            //tag.getGraphics().drawImage(src.getScaledInstance(widthdist, heightdist,  Image.SCALE_AREA_AVERAGING), 0, 0,  null);

            //标注水印
            //int x = widthdist/10*8;   //水印位置(x,y)
            //int y = heightdist/10*8;
            //jpg_logo( tag , x , y );

            //重命名并新建图片
            String oleName = imgsrc.substring(imgsrc.indexOf(".") - 1, imgsrc.indexOf("."));
            String newName = oleName + "v";
            String imgdist = imgsrc.replace(oleName, newName);
            //输出到文件流
            FileOutputStream out = new FileOutputStream(imgsrc);
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            //近JPEG编码
            encoder.encode(tag);
            out.close();

        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

九、类转换工具

package com.gpt.wechat.util;

import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.dozer.DozerBeanMapper;
import org.dozer.Mapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.util.CollectionUtils;

import java.io.Serializable;
import java.util.*;

/**
 * @author: zhaoxu
 */
public class BaseConverter {
    private static final Logger log = LoggerFactory.getLogger(BaseConverter.class);
    Mapper beanMapper = new DozerBeanMapper();

    public BaseConverter() {
    }

    public <S, D> D convertSingleObject(S source, Class<D> clazz) {
        if (source == null) {
            return null;
        } else {
            D dest = null;

            try {
                dest = beanMapper.map(source, clazz);
            } catch (Exception e) {
                log.error("初始化{}对象失败。", clazz, e);
            }

            return dest;
        }
    }

    public <S, D> List<D> convertMultiObjectToList(List<S> sourceList, Class<D> destClass) {
        if (CollectionUtils.isEmpty(sourceList)) {
            return null;
        } else {
            List<D> toList = new ArrayList<>();
            for (S src : sourceList) {
                toList.add(this.convertSingleObject(src, destClass));
            }
            return toList;
        }
    }

    public <S, D> PageResponse<D> convertMultiObjectToPage(Page<S> srcPages, Class<D> destClass) {
        PageResponse<D> pageResponse = new PageResponse<>();
        List<D> destList = new ArrayList<>();
        if (srcPages != null && srcPages.getContent() != null) {
            for (S srcPage : srcPages) {
                destList.add(this.convertSingleObject(srcPage, destClass));
            }
        }
        pageResponse.setTotal(srcPages.getTotalElements());
        pageResponse.setData(destList);
        pageResponse.setPageSize(srcPages.getSize());
        pageResponse.setCurrent(srcPages.getNumber() + 1);
        return pageResponse;
    }

    @Data
    @NoArgsConstructor
    public static class PageResponse<S> implements Serializable {
        private static final long serialVersionUID = -3355752076145642645L;
        /**
         * 总数
         */
        Long total;

        /**
         * 当前页
         */
        Integer current;

        /**
         * 每页条数
         */
        Integer pageSize;

        /**
         * 数据
         */
        List<S> data;
    }

}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1. Java工具概述 很多人初学程序时,总是在想,那么多的算法该怎么写呀?那么多的数据结构都不熟悉,该怎么实现呀?总是担心英语不好程序学不精通,数学不好写程序无法达到巅峰。学的程序越多,不懂的知识越多。 这种想法很正常,毕竟传统的计算机教育都是从原理开始的,科学原理一般理解起来还能够接受,但是实现起来都很难。计算机发展到了今天,能成为原理的基本已经有人实现了,今天我们学习任何知识都是站在巨人的肩膀上,只要理解程序运行原理,算法的功能即可。底层的各种算法,各种数据结构已经被“巨人们”实现了,一般都放在程序开发类库中,程序员开发过程中直接调用即可。 比如现在木工做家具,已经不存在自己砍树、加工木板、一点一点的雕刻了,如果需要木板,直接到市场上购买,需要各种图案,直接到市场购买,木工的工作就是把这些木板修理一下组装成一套家具即可。“工欲善其事,必先利其器”,在Java程序开发过程中,很多算法(比如:MD5加密算法)、很多数据结构(比如链表LinkedList)已经实现并且大多放在类库的java.util包中,程序员只需要了解各种工具的功能就可以直接调用。比如对一个数组进行排序,程序员可以写如下排序算法: 代码演示:数组排序 public static void sort(int[] arrs) { boolean isSwap = false; for (int i = 0; i < arrs.length - 1; i++) { isSwap = false; for (int j = arrs.length - 1; j > i; j--) { if (arrs[j - 1] > arrs[j]) { isSwap = true; int tmp = arrs[j - 1]; arrs[j - 1] = arrs[j]; arrs[j] = tmp; } } } } 该排序算法中只能对整数数组排序,还有其他数据类型呢?就需要重载很多方法进行排序操作。而在Java类库中有一个Arrays类的sort方法已经实现各种数据类型的排序算法。程序员只需要调用该类的方法即可。 代码演示:Arrays实现排序 public static void main(String[] args) { int[] ages={23, 45,12,76,34,56,24}; Arrays.sort(ages); for (int i = 0; i < ages.length; i++) { System.out.println(ages[i]); } } 在Java开发类库中,提供了很多工具类,我们即将学习最常见的工具类,比如对日期的操作,对集合的操作等。具体更多的工具类,请参考JavaDoc文档。 2. java.util.Date类 Date类包装了毫秒值,毫秒值表示自1970年1月1日00:00:00 GMT开始到现在经过的毫秒数。该类的大部分构造器和方法都已经过时,但是该类使用非常方便,因此目前使用还很普遍,该类的另一个主要功能是,在数据库操作中,它允许将毫秒值表示为SQL DATE值,是数据库操作中java.sql.Date的父类。关于数据库操作,将在第八章开始讲解。 该类目前推荐使用的构造方法有两个: 构造方法 说明 Date() 按照当前系统时间构造一个Date对象。 Date(long date) 按照给定的时间毫秒值构造一个 Date 对象。 表1 java.util.Date类的构造方法 主要的方法有: 返回 异常 说明 boolean after(Date when) 测试当前对象表示的时间是否在指定时间之后。 boolean before(Date when) 测试当前对象表示的时间是否在指定时间之前。 long getTime() 返回当前对象对应的时间毫秒值 void setTime(long time) 设置时间 表2 java.util.Date类的主要方法 代码演示:时间设置 public class Demo2 { public static void main(String[] args) { Date date=new Date(); ① date.setTime((10L*365+2)*24*60*60*1000); ② System.out.println(date); ③ } } 代码解析: ① 构造当前系统时间。 ② 设置时间值为1970年后10年的时间的毫秒值,10年间有2个闰年,10年的天数是:10*365+2,10L表示当前值是long类型。 ③ 调用Date的toString方法输出结果。 代码输出结果: Tue Jan 01 08:00:00 CST 1980 Q 老师,时间毫秒值从1970年1月1日0:00.000开始计算,上面示例中10年后应该是1980年1月1日0:00.000,为什么输出结果是:1980年1月1日 8:00呢? A java.util.Date类型表示的是GMT时间,本身输出是国际化输出,由于中国处于东八区时间,因此输出结果是早上8点。而Date的其他构造方法和普通方法的API都不容易实现国际化,因此目前Date类的大多数方法都被标识为过时,表示更灵活的时间类请参考java.util.Calendar。 Date的输出结果是按照国际通用格式输出的,而中国更习惯于“年-月-日”的形式输出,这种特殊格式的输出需要用到Java格式化工具。 3. 格式化工具 格式化的目的是把一个对象以不同的格式表示,以满足不同环境对格式的要求,比如:前面学习的Date对象实质是一个以毫秒值表示的时间,但是在不同的国家和地区表示方式不一样。那么就需要对Date进行格式化处理。接下来主要学习Java对日期时间的格式化和对数字的格式化处理。  日期时间格式化 Date类中包含了日期和时间,在Java编程中,日期通常指年、月、日,时间则指时、分、秒、毫秒。Java对Date进行格式化使用java.text.DateFormat类。在格式表示中,经常采用4种格式,这四种格式被定义为DateFormat类的常量。下表所示: 格式 说明 SHORT 以最短的格式表示,比如:09-8-20 MEDIUM 比short完整表示方式,比如:2009-8-20 LONG 比medium更完整的表示方式,比如:2009年8月20日 FULL 综合的表示方式,比如:2009年8月20日 星期四 表3 DateFormat的四种表示格式 因为不同国家地区需要格式化的结果不同,Locale类的对象表示了不同的区域,Locale定义目前全世界几乎所有地区的对象表示,比如: 格式 说明 Locale.CHINA 中国地区 Locale.US 美国地区 Locale.FRANCE 法国地区 Locale.CANADA 加拿大地区 表4 Locale对部分地区的表示 DateFormat是一个抽象类,不能直接实例化,可以使用下表中的静态方法得到DateFormat的对象。 方法 说明 getDateInstance() 返回默认地区,默认格式的关于日期的DateFormat对象。 getDateInstance(int) 返回指定格式下,默认地区的关于日期的DateFormat对象。 getDateInstance(int, Locale) 返回指定格式,指定地区的关于日期的DateFormat对象。 getTimeInstance() 返回默认地区,默认格式的关于时间的DateFormat对象。 getTimeInstance (int) 返回默认地区,指定格式的关于时间的DateFormat对象。 getTimeInstance (int, Locale) 返回指定地区,指定格式的关于时间的DateFormat对象。 getDateTimeInstance() 返回默认地区、默认日期格式、默认时间格式的关于日期和时间的DateFormat对象。 getDateTimeInstance (int,int) 返回默认地区、指定日期格式、指定时间格式的关于日期和时间的DateFormat对象。 getDateTimeInstance (int,int, Locale) 返回指定地区、指定日期格式、指定时间格式的关于日期和时间的DateFormat对象。 表5 获取DateFormat对象的静态方法 调用DateFormat对象的format方法可以把Date对象转换成为指定格式的String类型数据。比如: Date today=new Date(); DateFormat df=DateFormat.getDateInstance(DateFormat.FULL,Locale.CHINA); String result=df.format(today); 代码演示:日期的不同格式 import java.text.DateFormat; import java.util.Date; import java.util.Locale; public class Demo3 { public static void main(String[] args) { Date today = new Date(); Locale[] locals = new Locale[] { Locale.CHINA, Locale.US, Locale.UK }; for (int i = 0; i < locals.length; i++) { DateFormat df1 = DateFormat.getDateInstance(DateFormat.SHORT, locals[i]); DateFormat df2 = DateFormat.getDateInstance(DateFormat.MEDIUM, locals[i]); DateFormat df3 = DateFormat.getDateInstance(DateFormat.LONG, locals[i]); DateFormat df4 = DateFormat.getDateInstance(DateFormat.FULL, locals[i]); System.out.println(locals[i].getDisplayCountry() + "的日期形式:"); System.out.println("\tShort格式:" + df1.format(today)); System.out.println("\tMedium格式:" + df2.format(today)); System.out.println("\tLong格式:" + df3.format(today)); System.out.println("\tFull格式:" + df4.format(today)); } } } 代码输出结果: 中国的日期形式: Short格式:09-8-20 Medium格式:2009-8-20 Long格式:2009年8月20日 Full格式:2009年8月20日 星期四 美国的日期形式: Short格式:8/20/09 Medium格式:Aug 20, 2009 Long格式:August 20, 2009 Full格式:Thursday, August 20, 2009 英国的日期形式: Short格式:20/08/09 Medium格式:20-Aug-2009 Long格式:20 August 2009 Full格式:20 August 2009 在Java程序设计过程中,对应日期和时间的格式化,还有一个简单的格式化方式,就是java.text.SimpleDateFormat,该类中用字符串指定日期和时间的格式,字符串中的字符称为模式字符,模式字符区分大小写。常见的模式字符定义如下: 字母 日期或时间元素 y 年 M 年中的月份 w 年中的周数 W 月份中的周数 D 年中的天数 d 月份中的天数 F 月份中的星期 E 星期中的天数 a Am/pm 标记 H 一天中的小时数(0-23) k 一天中的小时数(1-24) K am/pm 中的小时数(0-11) h am/pm 中的小时数(1-12) m 小时中的分钟数 s 分钟中的秒数 S 毫秒数 表6 模式字符串 例如: 日期和时间模式 结果 "EEE, MMM d, ''yy" Wed, Jul 4, '01 "h:mm a" 12:08 PM "yyyy-MM-dd HH:mm:ss" 2009-8-20 14:22 "yyyy年MM月dd HH:mm:ss" 2009年8月20 14:22:23 表7 模式字符串示例 SimpleDateFormat是DateFormat的子类,用法和DateFormat类基本一致,主要使用format()方法。 代码演示:SimpleDateFormat进行日期转换 import java.text.SimpleDateFormat; import java.util.Date; public class Demo4 { public static void main(String[] args) { Date today = new Date(); SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat format2 = new SimpleDateFormat("yyyy年MM月dd HH:mm:ss"); SimpleDateFormat format3 = new SimpleDateFormat("HH:mm:ss"); SimpleDateFormat format4 = new SimpleDateFormat("yyyy"); System.out.println(format1.format(today)); System.out.println(format2.format(today)); System.out.println(format3.format(today)); System.out.println(format4.format(today)); } } 代码输出结果: 2009-08-20 2009年08月20 14:25:58 14:25:58 2009 在程序设计时,界面上用户输入的基本上都是字符串,如果字符串输入一个出生年月,如何把该字符串转换成Date类型呢?可以使用SimpleDateFormat的parse()方法。 代码演示:SimpleDateFormat解析日期 import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class Demo5 { public static void main(String[] args) { String birthday="1980-04-16"; SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd"); try { Date bir=format.parse(birthday); System.out.println(bir); } catch (ParseException e) { ① // TODO Auto-generated catch block e.printStackTrace(); } } } 代码解析: ① 用SimpleDateFormat解析日期的时候需要处理其中的ParseException异常。  数字格式化 对数字的格式化,在程序处理中也是非常常用的,数字格式化主要对小数点位数,表示的形式(比如:百分数表示)等格式处理。 NumberFormat 是所有数值格式的抽象基类。此类提供格式化和解析数值的接口。若要格式化当前Locale的数值,可使用其中一个方法: myString = NumberFormat.getInstance().format(myNumber); 若要格式化不同 Locale 的日期,可在调用getInstance方法时指定它。 NumberFormat nf = NumberFormat.getInstance(Locale.FRENCH); 方法 说明 getInstance() 获取常规数值格式。可以指定Local参数。 getNumberInstance() 获取常规数值格式。可以指定Local参数。 getIntegerInstance() 获取整数数值格式。可以指定Local参数。 getCurrencyInstance () 获取货币数值格式。可以指定Local参数。格式化后的数据前面会有一个货币符号,比如:“¥” getPercentInstance() 获取显示百分比的格式。可以指定Local参数。比如:小数 0.53 将显示为 53%。 表8 获取NumberFormat对象 代码演示:NumberFormat进行数字格式化 import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.Locale; public class Demo6 { public static void main(String[] args) { double mynum1 = 230456789; double mynum2 = 0.23; NumberFormat nf1 = NumberFormat.getInstance(Locale.CHINA); NumberFormat nf2 = NumberFormat.getCurrencyInstance(Locale.CHINA); NumberFormat nf3 = NumberFormat.getCurrencyInstance(Locale.US); NumberFormat nf4 = NumberFormat.getPercentInstance(); System.out.println(nf1.format(mynum1)); System.out.println(nf2.format(mynum1)); System.out.println(nf3.format(mynum1)); System.out.println(nf4.format(mynum2)); } } 代码输出结果: 230,456,789 ¥230,456,789.00 $230,456,789.00 23% 关于更复杂的数字格式化,可以使用java.text.DecimalFormat进行处理,该类通过模式字符串对数字格式化。 代码演示:DecimalFormat进行数字格式化 import java.text.DecimalFormat; public class Demo7 { public static void main(String[] args) { int num1=1234567; double num2=0.126543; DecimalFormat df1=new DecimalFormat("#,###"); ① DecimalFormat df2=new DecimalFormat("#.00"); ② DecimalFormat df3=new DecimalFormat("00.#"); ③ DecimalFormat df4=new DecimalFormat("0.##E0"); ④ DecimalFormat df5=new DecimalFormat("0.##%"); ⑤ System.out.println(df1.format(num1)); System.out.println(df2.format(num2)); System.out.println(df3.format(num2)); System.out.println(df4.format(num1)); System.out.println(df5.format(num2)); } } 代码解析: ① #:代表一个位置数字,如果该位置数字不存在,则省略不显示。 ,:代表数字中的分隔符,此示例用三位分隔一次。 ② 0:代表一个数字位置,如果该位置不存在,则用0来补充。小数中多余部分四舍五入。 .:表示小数点。 #:当前位置是0,则省略不显示。 ③ #:小数部分只显示1位小数,并且进行四舍五入。 ④ E:科学计数法。 ⑤ %:用百分数表示数字。 代码输出结果: 1,234,567 .13 00.1 1.23E6 12.65% 4. java.util.Calendar Calendar类是一个抽象类,它为特定的值诸如YEAR、MONTH、DAY_OF_MONTH、HOUR等日历字段之间的转换和操作日历字段(例如获得下星期的日期)提供了丰富的方法。并且可以非常方便的与Date类型进行相互转换。 使用静态方法getInstance()和getInstance(Locale locale)获取Calendar对象。Calendar定义了很多表示日期时间中各个部分的常量字段。 返回值 字段 说明 static int AM 指示从午夜到中午之前这段时间的 AM_PM 字段值。 static int DATE get 和 set 的字段,指示一个月中的某天。 static int DAY_OF_MONTH get 和 set 的字段,指示一个月中的某天。 static int DAY_OF_WEEK get 和 set 的字段,指示一个星期中的某天。 static int DAY_OF_YEAR get 和 set 的字段,指示当前年中的天数。 static int HOUR get 和 set 的字段,指示上午或下午的小时。 static int HOUR_OF_DAY get 和 set 的字段,指示一天中的小时。 static int MINUTE get 和 set 的字段,指示一小时中的分钟。 static int MONTH 指示月份的 get 和 set 的字段。 static int PM 指示从中午到午夜之前这段时间的 AM_PM 字段值。 static int SECOND get 和 set 的字段,指示一分钟中的秒。 static int WEEK_OF_MONTH get 和 set 的字段,指示当前月中的星期数。 static int WEEK_OF_YEAR get 和 set 的字段,指示当前年中的星期数。 static int YEAR 表示年的 get 和 set 的字段。 表9 Calendar类中的日期字段 Calendar类提供了丰富的操作方法,可以单独对年、月、日、时、分、秒等字段单独读取,也可以对星期设置,常用方法如下: 返回 方法 说明 void add(int field, int amount) 根据日历的规则,为给定的日历字段添加或减去指定的时间量。 boolean after(Object when) 判断此 Calendar 表示的时间是否在指定 Object 表示的时间之后,返回判断结果。 boolean before(Object when) 判断此 Calendar 表示的时间是否在指定 Object 表示的时间之前,返回判断结果。 int get(int field) 返回给定日历字段的值。 int getActualMaximum(int field) 给定此 Calendar 的时间值,返回指定日历字段可能拥有的最大值。 int getActualMinimum(int field) 给定此 Calendar 的时间值,返回指定日历字段可能拥有的最小值。 Date getTime() 返回一个表示此 Calendar 时间值(从历元至现在的毫秒偏移量)的 Date 对象。 long getTimeInMillis() 返回此 Calendar 的时间值,以毫秒为单位。 void set(int field, int value) 将给定的日历字段设置为给定值。 void set(int year, int month, int date) 设置日历字段 YEAR、MONTH 和 DAY_OF_MONTH 的值。 void set(int year, int month, int date, int hourOfDay, int minute) 设置日历字段 YEAR、MONTH、DAY_OF_MONTH、HOUR_OF_DAY 和 MINUTE 的值。 void set(int year, int month, int date, int hourOfDay, int minute, int second) 设置字段 YEAR、MONTH、DAY_OF_MONTH、HOUR、MINUTE 和 SECOND 的值。 void setTime(Date date) 使用给定的 Date 设置此 Calendar 的时间。 void setTimeInMillis(long millis) 用给定的 long 值设置此 Calendar 的当前时间值。 表10 Calendar类常用方法 代码演示:Calendar的使用 import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; public class Demo8 { public static void main(String[] args) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Calendar cale = Calendar.getInstance(); cale.set(2009, 8, 20);// 年月日同时设置 ① cale.set(Calendar.DAY_OF_WEEK, 2); ② Date date1 = cale.getTime(); ③ System.out.println(sdf.format(date1)); cale.set(Calendar.MONTH, 3); ④ cale.set(Calendar.DAY_OF_MONTH, 28); ⑤ cale.set(Calendar.YEAR, 1978); ⑥ Date date2 = cale.getTime(); System.out.println(sdf.format(date2)); } } 代码解析: ① 可以使用set方法对年月日时分秒同时设置。 ② 把天定位到星期一,Calendar中认为第一天是星期天,设置2就是星期一。 ③ Calendar类型转换为日期时间等价的Date类型。 ④ 单独设置月。 ⑤ 单独设置日。 ⑥ 单独设置年。 代码输出结果: 2009-09-21 17:21:37 1978-04-28 17:21:37 Q 老师,为什么通过Calendar设置月与输出差1个月? A 不是差一个月,而是在Calendar中对月份的计算是从0开始的,因此设置月份11其实就是中国的十二月。 5. Java对集合的操作 Java中学习了集合的操作,比如:排序、搜索等,Java中用java.util.Arrays对数组操作,使用java.util.Collections对集合框架中List操作。他们都是工具类,类中的方法全部都是静态方法。  Arrays中的方法 1. void Arrays.sort(T[]) 对数组中的元素按照升序进行排序。T代表某一数据类型。 代码演示:binarySearch使用 public static void main(String[] args) { int[] arrs=new int[]{12,54,12,8765,123,34,54,23,67}; Arrays.sort(arrs); for (int i : arrs) { System.out.print(i+" "); } } 代码输出结果: 12 12 23 34 54 54 67 123 8765 在sort方法中,遇到对象数组的排序时,要给对象提供排序的依据,实现Comparator接口,可以在接口的compare方法中指定排序规则,实现Comparator接口的对象称为比较器。 有一个Student类的数组,现在按照年龄进行升序排序,那么Comparator接口compare方法实现如下: 代码演示:compare重新按年龄实现 class Student { String name; int age; public Student(String name, int age) { super(); this.name = name; this.age = age; } public String toString() { return name + "," + age; } } class StuCom implements Comparator<Student> { ① public int compare(Student stu1, Student stu2) { ② if (stu1.age > stu2.age) { return 1; } else if (stu1.age == stu2.age) { return 0; } else { return -1; } } } public static void main(String[] args) { Student[] stus = new Student[] { new Student("小美", 21), new Student("阿聪", 22), new Student("武大郎", 28), new Student("阮小七", 26), new Student("晁盖", 30), new Student("鲁智深", 29), new Student("孙二娘", 26), new Student("扈三娘", 23), new Student("武松", 24) }; Arrays.sort(stus, new StuCom()); for (Student student : stus) { System.out.println(student); } } 代码解析: ① 定义一个比较器,必须实现Comparator接口,否则系统无法对一个对象数组进行搜索规则。 ② 实现Comparator接口的compare方法,对该方法中的两个参数进行比较,就是制定了比较的规则。 代码输出结果: 小美,21 阿聪,22 扈三娘,23 武松,24 阮小七,26 孙二娘,26 武大郎,28 鲁智深,29 晁盖,30 2. List Arrays.asList(Object[] objs) 把指定的数组转换为List的对象。 代码演示:asList使用 import java.util.Arrays; import java.util.List; public class Demo9 { public static void main(String[] args) { String[] strs={"aaa","bbb","ccc","ddd","eee","fff","ggg","hhh","iii","jjj"}; List list=Arrays.asList(strs); for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); } } } 3. int Arrays.binarySearch(T[] objs, key) 在数组objs中查找key的位置,返回key的下标,如果查找不到key,则返回负值。 int Arrays.binarySearch(T[] objs,int fromIndex,int toIndex , key) 在数组objs中从fromIndex到toIndex位置上查找key,返回key的下标,如果查找不到,返回一个负值。 在binarySearch方法调用之前一定要保证数组已经是排序的,如果没有排序,可以使用Arrays.sort(T[]) 进行排序,然后再进行查找。 代码演示:binarySearch使用 public static void main(String[] args) { String[] strs={"aaa","bbb","ccc","ddd","eee","fff","ggg","hhh","iii","jjj"}; Arrays.sort(strs); System.out.println(Arrays.binarySearch(strs, "ccc")); System.out.println(Arrays.binarySearch(strs, 4,8,"ggg")); System.out.println(Arrays.binarySearch(strs, 4,8,"aaa")); } 如果数组是一个自定义的对象数组,那么搜索之前要先指定比较器。 代码演示:binarySearch搜索对象使用 class StuCom implements Comparator<Student> { ① public int compare(Student stu1, Student stu2) { if (stu1.age > stu2.age) { return 1; } else if (stu1.age == stu2.age && stu1.name.equals(stu2.name)) { return 0; } else { return -1; } } } public static void main(String[] args) { Student[] stus = new Student[] { new Student("小美", 21), new Student("阿聪", 22), new Student("武大郎", 28), new Student("阮小七", 26), new Student("晁盖", 30), new Student("鲁智深", 29), new Student("孙二娘", 26), new Student("扈三娘", 23), new Student("武松", 24) }; Student s = new Student("晁盖", 30); System.out.println(Arrays.binarySearch(stus, s, new StuCom())); ② } 代码解析: ① 该比较器规定了要比较的类型就是Student类型,因此这里使用泛型。 ② 指定了对象数组,对象和比较器的方法进行搜索。结果返回搜索到的对象在数组中的下标。 除了上面介绍Arrays的方法外,还有一些其它的方法: 方法 说明 T[] copyOf(T[] t,int length) 把一个数组赋值到长度是length的新数组中。T表示数据类型。 fill(T[] t,N newValue) 用一个固定值填充数组中所有元素。 表11 Arrays其他常用方法。  Collections类 Collections类与Arrays类一样都提供了一系列的静态方法,只是Arrays主要操作数组,而Collections主要操作List集合,同时还有对Set的相关操作。 代码演示:Collections操作 import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Demo10 { static class Student implements Comparable { ① String name; int age; public Student(String name, int age) { super(); this.name = name; this.age = age; } public String toString() { return name + "," + age; } public int compareTo(Object o) { ② Student stu = (Student) o; if (this.age > stu.age) { return 1; } else if (this.age == stu.age && this.name.equals(stu.name)) { return 0; } else { return -1; } } } public static void main(String[] args) { List<Student> list = new ArrayList<Student>(); Student[] stus = new Student[] { new Student("小美", 21), new Student("阿聪", 22), new Student("武大郎", 28), new Student("阮小七", 26), new Student("晁盖", 30), new Student("鲁智深", 29), new Student("孙二娘", 26), new Student("扈三娘", 23), new Student("武松", 24) }; Collections.addAll(list, stus); ③ Collections.sort(list); ④ for (Student student : stus) { System.out.println(student); } Student stu = new Student("鲁智深", 29); int pos = Collections.binarySearch(list, stu); ⑤ System.out.println(pos); } } 代码解析: ① 在List中查找一个对象时,该对象必须实现Comparable接口。 ② compareTo方法中使用当前对象与参数对象进行比较。 ③ 把一个数组对象复制到List对象中用方法Collections.addAll(……)方法 ④ 对List集合中的元素按照自然顺序排序。 ⑤ 二分法查找,在List集合中查找Student对象,要求Student对象必须实现Comparable接口。 Collections的主要操作有: 1. int binarySearch(List<? extends Comparable<? super T>> list, T key) 该方法是寻找T对象在List中匹配元素的位置。要求List集合中必须全部都是T对象,T对象必须实现Comparable接口,如果查找成功返回对象在List中的位置,否则返回负数。该方法执行前首先要对List对象中的元素排序,该方法还有一个重载方法是: int binarySearch(List<? extends T> list, T key, Comparator<? super T> c) 该方法也是查找T对象在List中的位置,List集合中必须全部是T元素,但是不要去T必须实现Comparable接口,而是要求传入一个比较器。 2. sort(List<T> list) 对List中的元素按照自然排序。要按照用户自定义方式进行排序,必须实现Comparator接口。 sort (List<T> list, Comparator<? super T> c) 根据指定比较器产生的顺序对指定列表进行排序。 3. swap(List<?> list, int i, int j) 在指定列表的指定位置处交换元素。 4. reverse(List<?> list) 反转指定列表中元素的顺序。 在Collections中还有其他一些方法,可以参考JavaDoc文档。 6. java.lang.Math类 在java.lang.Math类中,包含用于执行基本数学运算的方法,如指数、对数、平方根和三角函数等。Math类中定义的所有方法和常量全部都是静态的,使用非常方便。定义的常量主要有两个:Math.E和Math.PI分别表示自然对数的底数和圆周率。 Math类中主要的方法有: 返回 方法 说明 static T abs(T a) 返回 long 值的绝对值。 static double acos(double a) 返回一个值的反余弦;返回的角度范围在 0.0 到 pi 之间。 static double atan(double a) 返回一个值的反正切;返回的角度范围在 -pi/2 到 pi/2 之间。 static double ceil(double a) 返回最小的(最接近负无穷大)double 值,该值大于等于参数,并等于某个整数。 static double cos(double a) 返回角的三角余弦。 static double floor(double a) 返回最大的(最接近正无穷大)double 值,该值小于等于参数,并等于某个整数。 static double log(double a) 返回 double 值的自然对数(底数是 e)。 static double log10(double a) 返回 double 值的底数为 10 的对数。 static T max(T a, T b) 返回两个 double 值中较大的一个。 static T min(T a, T b) 返回两个 long 值中较小的一个。 static T pow(T a, T b) 返回第一个参数的第二个参数次幂的值。 static double random() 返回带正号的 double 值,该值大于等于 0.0 且小于 1.0。 static int round(float a) 返回最接近参数的 int。 static double sin(double a) 返回角的三角正弦。 static double sqrt(double a) 返回正确舍入的 double 值的正平方根。 static double tan(double a) 返回角的三角正切。 表12 Math类中的常见静态方法
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值