Java常用简单工具方法util

集合并集

import java.util.LinkedHashSet;

public static void main(String[] args) {
    LinkedHashSet<Integer> set1 = new LinkedHashSet<>();
    set1.add(1);
    set1.add(3);
    System.out.println("set1: " + set1);

    LinkedHashSet<Integer> set2 = new LinkedHashSet<>();
    set2.add(2);
    set2.add(4);
    System.out.println("set2: " + set2);

    set2.addAll(set1);
    System.out.println(numbers);
}

生成随机小数

public static void main(String[] args) {
    double a = Math.random();
    System.out.println(a);
}

集合反转

public static void main(String[] args) {
    List<Integer> list = new ArrayList<Integer>();
    list.add(1);
    list.add(2);
    list.add(3);
    Collections.reverse(list);
    System.out.println(list);
}

冒泡排序

public static void main(String[] args) {
    int[] arr = {5,8,1,0,9,12,58,21};
    int n = arr.length;
    int temp = 0;
    for(int i=0; i < n; i++){
        for(int j=1; j < (n-i); j++){
            if(arr[j-1] > arr[j]){
               temp = arr[j-1];
               arr[j-1] = arr[j];
               arr[j] = temp;
            }
        }
    }
    System.out.println(Arrays.toString(arr));
}

字符串转日期

public static void main(String[] args) throws ParseException {
    String sDate="31/12/2022";
    Date date=new SimpleDateFormat("dd/MM/yyyy").parse(sDate);
    System.out.println(date);
}

字符串反转

public static void main(String[] args) {
    String str = "abcdefg";
    char[] s = str.toCharArray();
    int n = s.length;
    int halfLength = n / 2;
    for (int i=0; i<halfLength; i++){
        char temp = s[i];
        s[i] = s[n-1-i];
        s[n-1-i] = temp;
    }
    System.out.println(new String(s));
}

数组转集合

public static void main(String[] args) {
    String[] words = {"ace", "boom", "crew", "dog", "eon"};
    List<String> wordList = Arrays.asList(words);
    System.out.println(wordList);
}

获取当前机器IP地址

public static void main(String[] args) throws Exception {
    final DatagramSocket socket = new DatagramSocket();
    socket.connect(InetAddress.getByName("8.8.8.8"), 10002);
    String ip = socket.getLocalAddress().getHostAddress();
    System.out.println(ip);
}

替换字符串不区分大小写

public static void main(String[] args) {
    String target = "FOOtBall";
    target = target.replaceAll("(?i)foo", "");
    System.out.println(target);
}

发送带参数的http请求

public static void main(String[] args) throws Exception {
    String url = "http://www.baidu.com/";
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    con.setRequestMethod("GET");
    con.setRequestProperty("User-Agent", "Mozilla/5.0");
    int responseCode = con.getResponseCode();
    System.out.println("Response Code : " + responseCode);
    BufferedReader in = new BufferedReader(
            new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();
    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();
    System.out.println(response.toString());
    org.json.JSONObject responseJson = new org.json.JSONObject(response.toString());
    System.out.println("statusCode- "+responseJson.getString("statusCode"));
    System.out.println("statusMessage- "+responseJson.getString("statusMessage"));
    System.out.println("ipAddress- "+responseJson.getString("ipAddress"));
    System.out.println("countryCode- "+responseJson.getString("countryCode"));
    System.out.println("countryName- "+responseJson.getString("countryName"));
    System.out.println("regionName- "+responseJson.getString("regionName"));
    System.out.println("cityName- "+responseJson.getString("cityName"));
    System.out.println("zipCode- "+responseJson.getString("zipCode"));
    System.out.println("latitude- "+responseJson.getString("latitude"));
    System.out.println("longitude- "+responseJson.getString("longitude"));
    System.out.println("timeZone- "+responseJson.getString("timeZone"));
}

启动exe程序

public static void main(String[] args) throws Exception {
    String path = "C:/Program Files (x86)/Tencent/QQ/Bin/QQScLauncher.exe";
    Desktop desktop = Desktop.getDesktop();
    desktop.open(new File(path));
}

如果目录不存在则创建目录

public static void main(String[] args) throws Exception {
    String path = "D:/Program Files/hello";
    File folder = new File(path);
    if (!folder.exists()) {
        folder.mkdir();
    }
}

电子邮件格式验证

public static void main(String[] args) {
    String emailAdressen = "112233@qq.com";
    Pattern pattern = Pattern.compile("^[A-Z0-9_!#$%&'*+/=?`{|}~^-]+(?:\\.[A-Z0-9_!#$%&'*+/=?`{|}~^-]+↵\n" +
                ")*@[A-Z0-9-]+(?:\\.[A-Z0-9-]+)*$", Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(emailAdressen);
    System.out.println(matcher.find());
}

执行shell命令并打印输出

ProcessBuilder pb = new ProcessBuilder("ping", "localhost");
pb.inheritIO();
try {
    Process p = pb.start();
    int exitStatus = p.waitFor();
    System.out.println(exitStatus);
}
catch (InterruptedException | IOException x) {
    x.printStackTrace();
}

double四舍五入为2位小数

public static void main(String[] args) {
    BigDecimal bd = BigDecimal.valueOf(32.558);
    bd = bd.setScale(2, RoundingMode.HALF_UP);
    System.out.println(bd.doubleValue());
}

日期字符串中获取年月日

public static void main(String[] args) throws Exception {
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    Date parse = sdf.parse("10/12/2022");
    Calendar c = Calendar.getInstance();
    c.setTime(parse);
    System.out.println(c.get(Calendar.DATE));
    System.out.println(c.get(Calendar.MONTH)+1);
    System.out.println(c.get(Calendar.YEAR));
}

Xml转Map

public static Map<String, String> xmlToMap(String strXML) throws Exception {
        Map<String, String> data = new HashMap();
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        InputStream stream = new ByteArrayInputStream(strXML.getBytes("UTF-8"));
        Document doc = documentBuilder.parse(stream);
        doc.getDocumentElement().normalize();
        NodeList nodeList = doc.getDocumentElement().getChildNodes();

        for(int idx = 0; idx < nodeList.getLength(); ++idx) {
            Node node = nodeList.item(idx);
            if (node.getNodeType() == 1) {
                Element element = (Element)node;
                data.put(element.getNodeName(), element.getTextContent());
            }
        }

        try {
            stream.close();
        } catch (Exception var10) {
        }

        return data;
    }

Map转Xml

public static String mapToXml(Map<String, String> data) throws Exception {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.newDocument();
        Element root = document.createElement("xml");
        document.appendChild(root);
        Iterator var5 = data.keySet().iterator();

        while(var5.hasNext()) {
            String key = (String)var5.next();
            String value = (String)data.get(key);
            if (value == null) {
                value = "";
            }

            value = value.trim();
            Element filed = document.createElement(key);
            filed.appendChild(document.createTextNode(value));
            root.appendChild(filed);
        }

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        DOMSource source = new DOMSource(document);
        transformer.setOutputProperty("encoding", "UTF-8");
        transformer.setOutputProperty("indent", "yes");
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        transformer.transform(source, result);
        String output = writer.getBuffer().toString();

        try {
            writer.close();
        } catch (Exception var12) {
        }

        return output;
    }

带微信证书请求

public static String doWxSSLRequest(String url, String output, String wxMchId, String certPath) throws IOException, UnrecoverableKeyException, CertificateException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
        try {
            KeyStore clientStore = KeyStore.getInstance("PKCS12");
            // 读取证书
            InputStream pkIn = Thread.currentThread().getContextClassLoader().getResourceAsStream(certPath);
            try {
                // 指定PKCS12 密码
                clientStore.load(pkIn, wxMchId.toCharArray());
            } finally {
                pkIn.close();
            }
            KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
            kmf.init(clientStore, wxMchId.toCharArray());
            //添加信任
            javax.net.ssl.TrustManager[] tm = {new TrustManager()};
            //初始化 ;参数1为null,则不上传客户端证书(通常情况都是如此);
            SSLContext ctx = SSLContext.getInstance("SSL");
            ctx.init(kmf.getKeyManagers(), tm, new SecureRandom());

            SSLSocketFactory sf = ctx.getSocketFactory();

            URL requestUrl = new URL(null, url, new Handler());

            HttpsURLConnection connection = (HttpsURLConnection) requestUrl.openConnection();
            connection.setRequestProperty("Content-Type", "text/xml;charset=utf-8");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setSSLSocketFactory(sf);
            if (StringUtils.isNotEmpty(output)) {
                OutputStream outputStream = connection.getOutputStream();
                outputStream.write(output.getBytes("UTF-8"));
                outputStream.close();
            }
            //读取返回内容
            InputStream in = connection.getInputStream();
            InputStreamReader reader = new InputStreamReader(in, "UTF-8");
            BufferedReader bufferedReader = new BufferedReader(reader);
            String str = null;
            StringBuffer buffer = new StringBuffer();

            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            reader.close();
            in.close();
            in = null;
            connection.disconnect();
            ;

            return buffer.toString();

        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

static class TrustManager implements X509TrustManager {

        @Override
        public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

        }

        @Override
        public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    }

微信签名

public static String generateSignedXml(Map<String, String> data, String key, SignType signType) throws Exception {
        String sign = generateSignature(data, key, signType);
        data.put("sign", sign);
        return mapToXml(data);
    }


public static String generateSignature(Map<String, String> data, String key, SignType signType) throws Exception {
        Set<String> keySet = data.keySet();
        String[] keyArray = (String[])keySet.toArray(new String[keySet.size()]);
        Arrays.sort(keyArray);
        StringBuilder sb = new StringBuilder();
        String[] var6 = keyArray;
        int var7 = keyArray.length;

        for(int var8 = 0; var8 < var7; ++var8) {
            String k = var6[var8];
            if (!k.equals("sign") && ((String)data.get(k)).trim().length() > 0) {
                sb.append(k).append("=").append(((String)data.get(k)).trim()).append("&");
            }
        }

        sb.append("key=").append(key);
        if (SignType.MD5.equals(signType)) {
            return MD5(sb.toString()).toUpperCase();
        } else if (SignType.HMACSHA256.equals(signType)) {
            return HMACSHA256(sb.toString(), key);
        } else {
            throw new Exception(String.format("Invalid sign_type: %s", signType));
        }
    }




public static String MD5(String data) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] array = md.digest(data.getBytes("UTF-8"));
        StringBuilder sb = new StringBuilder();
        byte[] var4 = array;
        int var5 = array.length;

        for(int var6 = 0; var6 < var5; ++var6) {
            byte item = var4[var6];
            sb.append(Integer.toHexString(item & 255 | 256).substring(1, 3));
        }

        return sb.toString().toUpperCase();
    }

    public static String HMACSHA256(String data, String key) throws Exception {
        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
        sha256_HMAC.init(secret_key);
        byte[] array = sha256_HMAC.doFinal(data.getBytes("UTF-8"));
        StringBuilder sb = new StringBuilder();
        byte[] var6 = array;
        int var7 = array.length;

        for(int var8 = 0; var8 < var7; ++var8) {
            byte item = var6[var8];
            sb.append(Integer.toHexString(item & 255 | 256).substring(1, 3));
        }

        return sb.toString().toUpperCase();
    }
微信回调通知结果解密
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

/**
 * 微信退款结果通知内容解密
 */
public class WxRefundNotifyUtils {

    /**  密钥算法 */
    private static final String ALGORITHM = "AES";

    /**  加解密算法/工作模式/填充方式  */
    private static final String ALGORITHM_MODE_PADDING = "AES/ECB/PKCS5Padding";

    /** AES解密 */
    public static String decryptData(String base64Data,String password) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM_MODE_PADDING);
        SecretKeySpec key = new SecretKeySpec(MD5(password).toLowerCase().getBytes(), ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] decode = Base64.getDecoder().decode(base64Data);
        byte[] doFinal = cipher.doFinal(decode);
        return new String(doFinal,"utf-8");
    }

    public static String MD5(String input) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            return "check jdk";
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        char[] charArray = input.toCharArray();
        byte[] byteArray = new byte[charArray.length];
        for (int i = 0; i < charArray.length; i++) {
            byteArray[i] = (byte) charArray[i];
        }
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }
}

随机字符串

public static String generateNonceStr() {
        return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
    }

Base64转MultipartFile

public class Base64ToMultipartFile implements MultipartFile {
    private final byte[] imgContent;
    private final String header;

    public Base64ToMultipartFile (byte[] imgContent, String header) {
        this.imgContent = imgContent;
        this.header = header.split(";")[0];
    }

    @Override
    public String getName() {
        return System.currentTimeMillis() + Math.random() + "." + header.split("/")[1];
    }

    @Override
    public String getOriginalFilename() {
        return System.currentTimeMillis() + (int) Math.random() * 10000 + "." + header.split("/")[1];
    }

    @Override
    public String getContentType() {
        return header.split(":")[1];
    }

    @Override
    public boolean isEmpty() {
        return imgContent == null || imgContent.length == 0;
    }

    @Override
    public long getSize() {
        return imgContent.length;
    }

    @Override
    public byte[] getBytes() throws IOException {
        return imgContent;
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return new ByteArrayInputStream(imgContent);
    }

    @Override
    public void transferTo(File dest) throws IOException, IllegalStateException {
        new FileOutputStream(dest).write(imgContent);
    }

    /**
     * base64转multipartFile
     *
     * @param base64
     * @return
     */
    public static MultipartFile base64Convert(String base64) {
        String[] baseStrs = base64.split(",");
        Base64.Decoder decoder = Base64.getDecoder();
        byte[] b;
        b = decoder.decode(baseStrs[1]);
        for (int i = 0; i < b.length; ++i) {
            if (b[i] < 0) {
                b[i] += 256;
            }
        }
        return new Base64ToMultipartFile (b, baseStrs[0]);
    }
}
字符串驼峰下划线转换
public class CamelCaseTransform {

    /**
     * 将驼峰式命名的字符串转换为下划线方式。
     *
     * @param name 转换前的驼峰式命名的字符串
     * @return 转换后下划线命名的字符串
     */
    public static String underscoreName(String name) {
        StringBuilder result = new StringBuilder();
        if(name.contains("_")){
            throw new RuntimeException("已经是下划线分割了");
        }
        if (!StringUtils.isEmpty(name)) {
            // 循环字符
            for (int i = 0; i < name.length(); i++) {
                String s = name.substring(i, i + 1);
                // 在大写字母前添加下划线
                if (i != 0 && s.equals(s.toUpperCase()) && !Character.isDigit(s.charAt(0))) {
                    result.append("_");
                }
                result.append(s.toLowerCase());
            }
        }
        return result.toString();
    }

    /**
     * 将下划线大写方式命名的字符串转换为驼峰式。如果转换前的下划线大写方式命名的字符串为空,则返回空字符串。</br>
     * 例如:HELLO_WORLD->helloWorld
     *
     * @param name 转换前的下划线大写方式命名的字符串
     * @return 转换后的驼峰式命名的字符串
     */
    public static String camelName(String name) {
        StringBuilder result = new StringBuilder();
        if (!name.contains("_")) {
            // 不含下划线,仅将首字母小写
            return name.substring(0, 1).toLowerCase() + name.substring(1);
        }
        // 用下划线将原始字符串分割
        String camels[] = name.split("_");
        for (String camel : camels) {
            // 跳过原始字符串中开头、结尾的下换线或双重下划线
            if (StringUtils.isEmpty(camel)) {
                continue;
            }
            // 处理真正的驼峰片段
            if (result.length() == 0) {
                // 第一个驼峰片段,全部字母都小写
                result.append(camel.toLowerCase());
            } else {
                // 其他的驼峰片段,首字母大写
                result.append(camel.substring(0, 1).toUpperCase());
                result.append(camel.substring(1).toLowerCase());
            }
        }
        return result.toString();
    }

    /**
     * 将下划线大写方式命名的字符串转换为类名。如果转换前的下划线大写方式命名的字符串为空,则返回空字符串。</br>
     * 例如:HELLO_WORLD->HelloWorld
     *
     * @param name 转换前的下划线大写方式命名的字符串
     * @return 转换后的驼峰式命名的字符串
     */
    public static String camelClassName(String name) {
        StringBuilder result = new StringBuilder();
        if (!name.contains("_")) {
            // 不含下划线,仅将首字母小写
            return name.substring(0, 1).toUpperCase() + name.substring(1);
        }
        // 用下划线将原始字符串分割
        String camels[] = name.split("_");
        for (String camel : camels) {
            // 跳过原始字符串中开头、结尾的下换线或双重下划线
            if (StringUtils.isEmpty(camel)) {
                continue;
            }

            // 其他的驼峰片段,首字母大写
            result.append(camel.substring(0, 1).toUpperCase());
            result.append(camel.substring(1).toLowerCase());

        }
        return result.toString();
    }
}

Date转换

/**
     * Description:判断日期属于第几周
     *
     * @return
     * @author:FangTao
     * @date 2019/9/1113:57
     * @params string ,日期期间的最后一天
     **/
    public static String witchWeek(String datestr) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String s = datestr.substring(4, 6);
        Date date = sdf.parse(datestr);

        Calendar calendar = Calendar.getInstance();

        calendar.setTime(date);
        int weekOfMonth = calendar.get(Calendar.WEEK_OF_MONTH);
        String dayOfMonth_week = "第" + weekOfMonth + "周";

        return dayOfMonth_week;

    }


/**
     * 获得某月第一天
     * @param year
     * @param month
     * @return
     */
    public static String getFirstDayOfMonth(int year,int month){
        Calendar cal = Calendar.getInstance();
        //设置年份
        cal.set(Calendar.YEAR,year);
        //设置月份
        cal.set(Calendar.MONTH, month-1);
        //获取某月最小天数
        int firstDay = cal.getActualMinimum(Calendar.DAY_OF_MONTH);
        //设置日历中月份的最小天数
        cal.set(Calendar.DAY_OF_MONTH, firstDay);
        //格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String firstDayOfMonth = sdf.format(cal.getTime());
        return firstDayOfMonth;
    }


/**
     * 获得某月最后一天
     * @param year
     * @param month
     * @return
     */
    public static String getLastDayOfMonth(int year,int month){
        Calendar cal = Calendar.getInstance();
        //设置年份
        cal.set(Calendar.YEAR,year);
        //设置月份
        cal.set(Calendar.MONTH, month-1);
        //获取某月最大天数
        int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
        //设置日历中月份的最大天数
        cal.set(Calendar.DAY_OF_MONTH, lastDay);
        //格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String lastDayOfMonth = sdf.format(cal.getTime());
        return lastDayOfMonth;
    }


/**
     * 获取某一时间段特定星期几的日期
     * @param beginDate 开始日期
     * @param endDate 结束日期
     * @param weekDays 星期
     *
     * @return 返回时间数组
     */
    public static List<String> getDates(String beginDate, String endDate, String weekDays) {
        long time = 1L;
        long perDayMilSec = 24 * 60 * 60 * 1000;
        List<String> dateList = new ArrayList<String>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //需要查询的星期系数
        String strWeekNumber = weekForNum(weekDays);
        try {
            beginDate = sdf.format(sdf.parse(beginDate).getTime() - perDayMilSec);
            while (true) {
                time = sdf.parse(beginDate).getTime();
                time = time + perDayMilSec;
                Date date = new Date(time);
                beginDate = sdf.format(date);
                if (beginDate.compareTo(endDate) <= 0) {
                    //查询的某一时间的星期系数
                    Integer weekDay = dayForWeek(date);
                    //判断当期日期的星期系数是否是需要查询的
                    if (strWeekNumber.indexOf(weekDay.toString()) != -1) {
                        dateList.add(beginDate);
                    }
                } else {
                    break;
                }
            }
        } catch (ParseException e1) {
            e1.printStackTrace();
        }
        return dateList;
    }

/**
     * 根据日期获取 星期
     *
     * @param datetime
     * @return
     */
    public static String dateToWeek(String datetime) {

        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
        String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        Calendar cal = Calendar.getInstance();
        Date date;
        try {
            date = f.parse(datetime);
            cal.setTime(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //一周的第几天
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0) {
            w = 0;
        }
        return weekDays[w];
    }


/**
     * 获取时间差 天
     * @param begin_date
     * @param end_date
     * @return
     * @throws Exception
     */
    public static int getInterval(Date begin_date, Date end_date) throws Exception {
        int day = 0;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        if (begin_date != null) {
            String begin = sdf.format(begin_date);
            begin_date = sdf.parse(begin);
        }
        if (end_date != null) {
            String end = sdf.format(end_date);
            end_date = sdf.parse(end);
        }
        day = (int) ((end_date.getTime() - begin_date.getTime()) / (24 * 60 * 60 * 1000));
        return day;
    }

/**
     * 根据年月日计算年龄,birthTimeString:"1994-11-14"
     */
    public static int getAgeFromBirthTime(String birthTimeString) {
        // 先截取到字符串中的年、月、日
        String strs[] = birthTimeString.trim().split("-");
        int selectYear = Integer.parseInt(strs[0]);
        // 获得当前时间的年、月、日
        Calendar cal = Calendar.getInstance();
        int yearNow = cal.get(Calendar.YEAR);
        // 用当前年 减去 生日年 .不用计算月日 例:2022的在2022年都是0岁
        if (selectYear > yearNow) {
            return 0;
        }
        return yearNow - selectYear;
    }

/**
     * 判断时间是否整时
     */
    public static Boolean isHour(Date date) {
        SimpleDateFormat myFmt = new SimpleDateFormat("mmss");
        String mmss = myFmt.format(date);
        return "0000".equals(mmss);
    }

/**
     * 获取整时  08:30--->08:00
     */
    public static Date getWholeDate(Date date) throws Exception {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:00:00");
        String time1 = formatter.format(date);
        return formatter.parse(time1);

    }

/**
     * 增加一个小时  08:00--->09:00
     */
    public static Date addHousr(Date date) throws Exception {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.HOUR, 1);// 24小时制
        return cal.getTime();
    }

/**
     * 获取当天剩余秒数
     */
    public static Integer getRemainSecondsDay() {
        Date currentDate = new Date();
        LocalDateTime midnight = LocalDateTime.ofInstant(currentDate.toInstant(),
                ZoneId.systemDefault()).plusDays(1).withHour(0).withMinute(0)
                .withSecond(0).withNano(0);
        LocalDateTime currentDateTime = LocalDateTime.ofInstant(currentDate.toInstant(),
                ZoneId.systemDefault());
        return (int) ChronoUnit.SECONDS.between(currentDateTime, midnight);
    }

获取IP地址

/**
	 * 获取 IP地址
	 * 使用 Nginx等反向代理软件, 则不能通过 request.getRemoteAddr()获取 IP地址
	 * 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,
	 * X-Forwarded-For中第一个非 unknown的有效IP字符串,则为真实IP地址
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
	}

MD5

public class MD5Utils {

    private static final String hexDigIts[] = {"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"};

    /**
     * MD5加密
     * @param origin 字符
     * @param charsetname 编码
     * @return
     */
    public static String MD5Encode(String origin, String charsetname){
        String resultString = null;
        try{
            resultString = new String(origin);
            MessageDigest md = MessageDigest.getInstance("MD5");
            if(null == charsetname || "".equals(charsetname)){
                resultString = byteArrayToHexString(md.digest(resultString.getBytes()));
            }else{
                resultString = byteArrayToHexString(md.digest(resultString.getBytes(charsetname)));
            }
        }catch (Exception e){
        }
        return resultString;
    }


    public static String byteArrayToHexString(byte b[]){
        StringBuffer resultSb = new StringBuffer();
        for(int i = 0; i < b.length; i++){
            resultSb.append(byteToHexString(b[i]));
        }
        return resultSb.toString();
    }

    public static String byteToHexString(byte b){
        int n = b;
        if(n < 0){
            n += 256;
        }
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigIts[d1] + hexDigIts[d2];
    }

    /**
     * 签名算法
     *
     * @param parameters 签名参数
     * @return
     */
    public static String createSign(SortedMap<Object, Object> parameters, String appSecret) {
        StringBuffer stringBuffer = new StringBuffer();
        //所有参与传参的参数按照accsii排序(升序)
        Set es = parameters.entrySet();
        Iterator it = es.iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            Object v = entry.getValue();
            if (null != v && !"".equals(v)) {
                stringBuffer.append(v);
            }
        }
        stringBuffer.append(appSecret);
        String sign = MD5Utils.MD5Encode(stringBuffer.toString(), "UTF-8").toLowerCase();
        return sign;
    }

}

手机号校验

public static boolean checkPhone(String phone){
        Pattern p = Pattern.compile("^[1](([3-9][\\d])|([4][5,6,7,8,9])|([6][5,6])|([7][3,4,5,6,7,8])|([9][8,9]))[\\d]{8}$");
        if(p.matcher(phone).matches()){
            return true;
        }
        return false;
    }

拼音处理

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.exception.BadHanyuPinyinOutputFormatCombination;

/**
 * @author SuJinLiang
 * @description 汉字转拼音 工具类
 * @date 2021/10/27
 */
public class PinYinUtil {

    /**
     * 获取字符串拼音的第一个字母
     * @param chinese
     * @return
     */
    public static String toFirstChar(String chinese){
        String pinyinStr = "";
        char[] newChar = chinese.toCharArray();  //转为单个字符
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (int i = 0; i < newChar.length; i++) {
            if (newChar[i] > 128) {
                try {
                    pinyinStr += PinyinHelper.toHanyuPinyinStringArray(newChar[i], defaultFormat)[0].charAt(0);
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            }else{
                pinyinStr += newChar[i];
            }
        }
        return pinyinStr;
    }

    /**
     * 汉字转为拼音
     * @param chinese
     * @return
     */
    public static String toPinyin(String chinese){
        String pinyinStr = "";
        char[] newChar = chinese.toCharArray();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (int i = 0; i < newChar.length; i++) {
            if (newChar[i] > 128) {
                try {
                    pinyinStr += PinyinHelper.toHanyuPinyinStringArray(newChar[i], defaultFormat)[0];
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            }else{
                pinyinStr += newChar[i];
            }
        }
        return pinyinStr;
    }

Base64转图片

public static void base64ToFile() {
        // 解密
        try {
            String file = "data:image/png;base64,iVBORw0KGgo...";
            // 绝对路径
            String savePath = "C:\\Users\\Administrator\\Desktop\\";
            // 图片路径+图片名+图片后缀
            String imgClassPath = savePath.concat(UUID.randomUUID().toString()).concat(".jpg");
            // 解密
            Base64.Decoder decoder = Base64.getDecoder();
            // 去掉base64前缀 data:image/jpeg;base64,
            file = file.substring(file.indexOf(",", 1) + 1, file.length());
            byte[] b = decoder.decode(file);
            // 处理数据
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            // 保存图片
            OutputStream out = new FileOutputStream(imgClassPath);
            out.write(b);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

文件url地址转File

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public static File urlToFile(URL url) {
        InputStream is = null;
        File file = null;
        FileOutputStream fos = null;
        try {
            file = File.createTempFile("tmp", null);
            URLConnection urlConn = null;
            urlConn = url.openConnection();
            is = urlConn.getInputStream();
            fos = new FileOutputStream(file);
            byte[] buffer = new byte[4096];
            int length;
            while ((length = is.read(buffer)) > 0) {
                fos.write(buffer, 0, length);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
            }
        }
        return file;
    }

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
常用Java工具类有很多,以下是一些常见的工具类: 1. org.apache.commons.io.IOUtils:提供了一组用于处理输入输出流的实用方法,如复制流、关闭流等。\[1\] 2. org.apache.commons.io.FileUtils:提供了一组用于操作文件和目录的实用方法,如复制文件、删除文件等。\[2\] 3. org.apache.commons.lang.StringUtils:提供了一组用于处理字符串的实用方法,如判断字符串是否为空、去除字符串中的空格等。\[3\] 4. org.apache.http.util.EntityUtils:提供了一组用于处理HTTP实体的实用方法,如获取实体内容、解析实体等。 5. org.apache.commons.lang3.StringUtils:是Apache Commons Lang库的一部分,提供了更多字符串处理的实用方法,如判断字符串是否为数字、反转字符串等。 6. org.apache.commons.io.FilenameUtils:提供了一组用于处理文件名的实用方法,如获取文件名的扩展名、合并路径等。 7. org.springframework.util.StringUtils:是Spring框架中的一个工具类,提供了一组用于处理字符串的实用方法,如判断字符串是否为空、去除字符串中的空格等。 8. org.apache.commons.lang.ArrayUtils:提供了一组用于处理数组的实用方法,如判断数组是否为空、合并数组等。 这些工具类可以帮助开发人员简化代码,提高开发效率。具体使用哪些工具类取决于项目需求和个人偏好。 #### 引用[.reference_title] - *1* *3* [【JavaJava中的常用工具类(排名前 16)](https://blog.csdn.net/u011397981/article/details/129688782)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [「Java工具类」验证码工具java生成验证码工具类](https://blog.csdn.net/lxn39830435731415926/article/details/121259382)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值