IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Java知识库 -> 【整理Java相关的工具类,持续更新中,建议收藏】 -> 正文阅读

[Java知识库]【整理Java相关的工具类,持续更新中,建议收藏】

下载地址:


BigDecimalUtilBigDecimalUtil计算工具类
CaptchaUtil图片验证码工具类
CoordinateTransformUtil坐标系转换工具类
DateUtil日期加减工具类
EmailUtilemail发送工具类
EncodeDecodeUtil加密工具类
GzipUtil压缩工具类
HttpClienthttp远程调用工具类
JwtUtiljwt工具类
LanguageUtil语种工具类
MD5MD5加密工具类
ObjectDeepCopyUtil对象深度拷贝工具类
OrderNoUtil订单号工具类
PoolPrintUtil线程池打印工具类
RandomUtil手机验证码生成工具类
ResponseEntity统一结果返回类
ResponseUtil结果响应工具类
XmlUtilxml转换map工具类

持续更新中…




1.BigDecimalUtil

public class BigDecimalUtil {

    /**
     * x, y转成BigDecimal后相减
     * @param x x值(double类型)
     * @param y y值 (double类型)
     * @return result
     */
    public static double subtract(double x, double y) {
        BigDecimal d1 = BigDecimal.valueOf(x);
        BigDecimal d2 = BigDecimal.valueOf(y);
        return d1.subtract(d2).doubleValue();
    }

    /**
     * x, y转成BigDecimal后相减,获得的结果再向上取整
     * @param x x值(double类型)
     * @param y y值 (double类型)
     * @return result
     */
    public static double subtractUp(double x, double y) {
        double value = subtract(x, y);
        return roundUp(value);
    }

    /**
     * x, y转成BigDecimal后相减,获得的结果再向下取整
     * @param x x值(double类型)
     * @param y y值 (double类型)
     * @return result
     */
    public static double subtractDown(double x, double y) {
        double value = subtract(x, y);
        return roundDown(value);
    }

    /**
     * x, y转成BigDecimal后相减
     * @param x x值(double类型)
     * @param y y值 (double类型)
     * @return result
     */
    public static double add(double x, double y) {
        BigDecimal d1 = BigDecimal.valueOf(x);
        BigDecimal d2 = BigDecimal.valueOf(y);
        return d1.add(d2).doubleValue();
    }

    /**
     * x, y转成BigDecimal后相乘
     * @param x x值(double类型)
     * @param y y值 (double类型)
     * @return result
     */
    public static double multiply(double x, double y) {
        BigDecimal d1 = BigDecimal.valueOf(x);
        BigDecimal d2 = BigDecimal.valueOf(y);
        return d1.multiply(d2).doubleValue();
    }

    /**
     * x, y转成BigDecimal后相除
     * @param x x值(double类型)
     * @param y y值 (double类型)
     * @return result
     */
    public static double divide(double x, double y, int scale) {
        BigDecimal d1 = BigDecimal.valueOf(x);
        BigDecimal d2 = BigDecimal.valueOf(y);
        return d1.divide(d2, scale).doubleValue();
    }

    /**
     * 向上取整,整数向上取整
     * @param val val
     * @return result
     */
    public static double roundUp(double val) {
        return roundUp(val, 0);
    }


    /**
     * 向上取整,可设置精度
     * @param val val
     * @param scale 精度
     * @return result
     */
    public static double roundUp(double val, int scale) {
        BigDecimal dec = BigDecimal.valueOf(val);
        return dec.setScale(scale, RoundingMode.UP).doubleValue();
    }

    /**
     * 向下取整,可设置精度
     * @param val val
     * @return result
     */
    public static double roundDown(double val) {
        return roundDown(val, 0);
    }

    /**
     * 向下取整,可设置精度
     * @param val val
     * @param scale 精度
     * @return result
     */
    public static double roundDown(double val, int scale) {
        BigDecimal dec = BigDecimal.valueOf(val);
        return dec.setScale(scale, RoundingMode.DOWN).doubleValue();
    }

    /**
     * 四舍五入
     * @param val val
     * @return result
     */
    public static double roundHalfUp(double val) {
        return roundHalfUp(val, 0);
    }

    /**
     * 四舍五入,可设置精度
     * @param val
     * @param scale
     * @return
     */
    public static double roundHalfUp(double val, int scale) {
        BigDecimal dec = BigDecimal.valueOf(val);
        return dec.setScale(scale, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

}

2.CaptchaUtil 图片验证码工具类

public class CaptchaUtil {

    static char[] chars = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
            'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
            'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};

    /**
     * 生成一个位数为count的随机验证码
     *
     * @param count
     * @return
     */
    public static String genCaptcha(int count) {
        StringBuilder captcha = new StringBuilder();

        for (int i = 0; i < count; i++) {
            char c = chars[ThreadLocalRandom.current().nextInt(chars.length)];//随机选取一个字母或数字
            captcha.append(c);
        }
        return captcha.toString();
    }

    /**
     * 为一个验证码生成一个图片
     * <p>
     * 特性:
     * - 颜色随机
     * - 上下位置随机
     * - 左右位置随机,但字符之间不会重叠
     * - 左右随机旋转一个角度
     * - 避免字符出界
     * - 随机颜色的小字符做背景干扰
     * - 根据字符大小自动调整图片大小、自动计算干扰字符的个数
     *
     * @param captcha
     * @return
     * @author XuJijun
     */
    public static BufferedImage genCaptchaImg(String captcha) {
        ThreadLocalRandom r = ThreadLocalRandom.current();

        int count = captcha.length();
        int fontSize = 80; //code的字体大小
        int fontMargin = fontSize / 4; //字符间隔
        int width = (fontSize + fontMargin) * count + fontMargin; //图片长度
        int height = (int) (fontSize * 1.2); //图片高度,根据字体大小自动调整;调整这个系数可以调整字体占图片的比例
        int avgWidth = width / count;    //字符平均占位宽度
        int maxDegree = 26;    //最大旋转度数

        //背景颜色
        Color bkColor = Color.WHITE;
        //验证码的颜色
        Color[] catchaColor = {Color.MAGENTA, Color.BLACK, Color.BLUE, Color.CYAN, Color.GREEN, Color.ORANGE, Color.PINK};

        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = image.createGraphics();

        //填充底色为灰白
        g.setColor(bkColor);
        g.fillRect(0, 0, width, height);

        //画边框
        g.setColor(Color.WHITE);
        g.drawRect(0, 0, width - 1, height - 1);

        //画干扰字母、数字
        int dSize = fontSize / 3; //调整分母大小以调整干扰字符大小
        Font font = new Font("Fixedsys", Font.PLAIN, dSize);
        g.setFont(font);
        int dNumber = width * height / dSize / dSize;//根据面积计算干扰字母的个数
        for (int i = 0; i < dNumber; i++) {
            char d_code = chars[r.nextInt(chars.length)];
            g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));
            g.drawString(String.valueOf(d_code), r.nextInt(width), r.nextInt(height));
        }

        //开始画验证码:

        // 创建字体
        font = new Font(Font.MONOSPACED, Font.ITALIC | Font.BOLD, fontSize);
        // 设置字体
        g.setFont(font);

        for (int i = 0; i < count; i++) {
            char c = captcha.charAt(i);
            g.setColor(catchaColor[r.nextInt(catchaColor.length)]);//随机选取一种颜色

            //随机旋转一个角度[-maxDegre, maxDegree]
            int degree = r.nextInt(-maxDegree, maxDegree + 1);

            //偏移系数,和旋转角度成反比,以避免字符在图片中越出边框
            double offsetFactor = 1 - (Math.abs(degree) / (maxDegree + 1.0));//加上1,避免出现结果为0

            g.rotate(degree * Math.PI / 180); //旋转一个角度
            int x = (int) (fontMargin + r.nextInt(avgWidth - fontSize) * offsetFactor); //横向偏移的距离
            int y = (int) (fontSize + r.nextInt(height - fontSize) * offsetFactor); //上下偏移的距离

            g.drawString(String.valueOf(c), x, y); //x,y是字符的左下角,偏离原点的距离!!!

            g.rotate(-degree * Math.PI / 180); //画完一个字符之后,旋转回原来的角度
            g.translate(avgWidth, 0);//移动到下一个画画的原点
            //System.out.println(c+": x="+x+" y="+y+" degree="+degree+" offset="+offsetFactor);

            //X、Y坐标在合适的范围内随机,不旋转:
            //g.drawString(String.valueOf(c), width/count*i+r.nextInt(width/count-fontSize), fontSize+r.nextInt(height-fontSize));
        }

        g.dispose();

        return image;
    }
}

3.CoordinateTransformUtil 坐标系转换工具类

public class CoordinateTransformUtil {
    static double x_pi = 3.14159265358979324 * 3000.0 / 180.0;
    // π
    static double pi = 3.1415926535897932384626;
    // 长半轴
    static double a = 6378245.0;
    // 扁率
    static double ee = 0.00669342162296594323;


    /**
     * 将原本坐标系的经纬度转换成新的坐标系的经纬度
     * @param newCoordinateType 新坐标系,如baidu,wgs84
     * @param originalCoordinateType 原坐标系,如baidu,wgs84
     * @param lat 原纬度
     * @param lon 原经度
     * @return 新坐标系的经纬度
     */
    public static double[] convertLatLonByCoordinate(String newCoordinateType, String originalCoordinateType, double lat, double lon) {
        if (originalCoordinateType == null) {
            return null;
        }

        boolean bd09ToWgs84 = (originalCoordinateType.equalsIgnoreCase("bd09") || originalCoordinateType.equalsIgnoreCase("baidu")
                && (newCoordinateType.equalsIgnoreCase("google")) || newCoordinateType.equalsIgnoreCase("wgs84"));
        boolean gcj02toWgs84 = (originalCoordinateType.equalsIgnoreCase("gaode") || originalCoordinateType.equalsIgnoreCase("gcj02")
                && (newCoordinateType.equalsIgnoreCase("google")) || newCoordinateType.equalsIgnoreCase("wgs84"));

        boolean wgs84ToBd09 = (originalCoordinateType.equalsIgnoreCase("google") || originalCoordinateType.equalsIgnoreCase("wgs84"))
                && (newCoordinateType.equalsIgnoreCase("bd09") || newCoordinateType.equalsIgnoreCase("baidu"));
        boolean gcj02ToBd09 = (originalCoordinateType.equalsIgnoreCase("gaode") || originalCoordinateType.equalsIgnoreCase("gcj02"))
                && (newCoordinateType.equalsIgnoreCase("bd09") || newCoordinateType.equalsIgnoreCase("baidu"));

        boolean wgs84ToGcj02 = (originalCoordinateType.equalsIgnoreCase("google") || originalCoordinateType.equalsIgnoreCase("wgs84"))
                && (newCoordinateType.equalsIgnoreCase("gaode") || newCoordinateType.equalsIgnoreCase("gcj02"));
        boolean bd09ToGcj02 = (originalCoordinateType.equalsIgnoreCase("bd09") || originalCoordinateType.equalsIgnoreCase("baidu"))
                && (newCoordinateType.equalsIgnoreCase("gaode") || newCoordinateType.equalsIgnoreCase("gcj02"));

        if (originalCoordinateType.equals(newCoordinateType)) {
            return new double[]{lat, lon};
        } else if (bd09ToWgs84) {
            return bd09towgs84(lon, lat);
        } else if (gcj02toWgs84) {
            return gcj02towgs84(lon, lat);
        } else if (wgs84ToBd09) {
            return wgs84tobd09(lon, lat);
        } else if (gcj02ToBd09) {
            return gcj02tobd09(lon, lat);
        } else if (wgs84ToGcj02) {
            return wgs84togcj02(lon, lat);
        } else if (bd09ToGcj02) {
            return bd09togcj02(lon, lat);
        } else {
            return null;
        }
    }

    /**
     * 百度坐标系(BD-09)转WGS坐标
     *
     * @param lng 百度坐标纬度
     * @param lat 百度坐标经度
     * @return WGS84坐标数组
     */
    public static double[] bd09towgs84(double lng, double lat) {
        double[] gcj = bd09togcj02(lng, lat);
        double[] wgs84 = gcj02towgs84(gcj[0], gcj[1]);
        return wgs84;
    }

    /**
     * WGS坐标转百度坐标系(BD-09)
     *
     * @param lng WGS84坐标系的经度
     * @param lat WGS84坐标系的纬度
     * @return 百度坐标数组
     */
    public static double[] wgs84tobd09(double lng, double lat) {
        double[] gcj = wgs84togcj02(lng, lat);
        double[] bd09 = gcj02tobd09(gcj[0], gcj[1]);
        return bd09;
    }

    /**
     * 火星坐标系(GCJ-02)转百度坐标系(BD-09)
     *
     * 谷歌、高德——>百度
     * @param lng 火星坐标经度
     * @param lat 火星坐标纬度
     * @return 百度坐标数组
     */
    public static double[] gcj02tobd09(double lng, double lat) {
        double z = Math.sqrt(lng * lng + lat * lat) + 0.00002 * Math.sin(lat * x_pi);
        double theta = Math.atan2(lat, lng) + 0.000003 * Math.cos(lng * x_pi);
        double bd_lng = z * Math.cos(theta) + 0.0065;
        double bd_lat = z * Math.sin(theta) + 0.006;
        return new double[] { bd_lng, bd_lat };
    }

    /**
     * 百度坐标系(BD-09)转火星坐标系(GCJ-02)
     *
     * 百度——>谷歌、高德
     * @param bd_lon 百度坐标纬度
     * @param bd_lat 百度坐标经度
     * @return 火星坐标数组
     */
    public static double[] bd09togcj02(double bd_lon, double bd_lat) {
        double x = bd_lon - 0.0065;
        double y = bd_lat - 0.006;
        double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
        double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
        double gg_lng = z * Math.cos(theta);
        double gg_lat = z * Math.sin(theta);
        return new double[] { gg_lng, gg_lat };
    }

    /**
     * WGS84转GCJ02(火星坐标系)
     *
     * @param lng WGS84坐标系的经度
     * @param lat WGS84坐标系的纬度
     * @return 火星坐标数组
     */
    public static double[] wgs84togcj02(double lng, double lat) {
        if (out_of_china(lng, lat)) {
            return new double[] { lng, lat };
        }
        double dlat = transformlat(lng - 105.0, lat - 35.0);
        double dlng = transformlng(lng - 105.0, lat - 35.0);
        double radlat = lat / 180.0 * pi;
        double magic = Math.sin(radlat);
        magic = 1 - ee * magic * magic;
        double sqrtmagic = Math.sqrt(magic);
        dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * pi);
        dlng = (dlng * 180.0) / (a / sqrtmagic * Math.cos(radlat) * pi);
        double mglat = lat + dlat;
        double mglng = lng + dlng;
        return new double[] { mglng, mglat };
    }

    /**
     * GCJ02(火星坐标系)转GPS84
     *
     * @param lng 火星坐标系的经度
     * @param lat 火星坐标系纬度
     * @return WGS84坐标数组
     */
    public static double[] gcj02towgs84(double lng, double lat) {
        if (out_of_china(lng, lat)) {
            return new double[] { lng, lat };
        }
        double dlat = transformlat(lng - 105.0, lat - 35.0);
        double dlng = transformlng(lng - 105.0, lat - 35.0);
        double radlat = lat / 180.0 * pi;
        double magic = Math.sin(radlat);
        magic = 1 - ee * magic * magic;
        double sqrtmagic = Math.sqrt(magic);
        dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * pi);
        dlng = (dlng * 180.0) / (a / sqrtmagic * Math.cos(radlat) * pi);
        double mglat = lat + dlat;
        double mglng = lng + dlng;
        return new double[] { lng * 2 - mglng, lat * 2 - mglat };
    }

    /**
     * 纬度转换
     *
     * @param lng
     * @param lat
     * @return
     */
    public static double transformlat(double lng, double lat) {
        double ret = -100.0 + 2.0 * lng + 3.0 * lat + 0.2 * lat * lat + 0.1 * lng * lat + 0.2 * Math.sqrt(Math.abs(lng));
        ret += (20.0 * Math.sin(6.0 * lng * pi) + 20.0 * Math.sin(2.0 * lng * pi)) * 2.0 / 3.0;
        ret += (20.0 * Math.sin(lat * pi) + 40.0 * Math.sin(lat / 3.0 * pi)) * 2.0 / 3.0;
        ret += (160.0 * Math.sin(lat / 12.0 * pi) + 320 * Math.sin(lat * pi / 30.0)) * 2.0 / 3.0;
        return ret;
    }

    /**
     * 经度转换
     *
     * @param lng
     * @param lat
     * @return
     */
    public static double transformlng(double lng, double lat) {
        double ret = 300.0 + lng + 2.0 * lat + 0.1 * lng * lng + 0.1 * lng * lat + 0.1 * Math.sqrt(Math.abs(lng));
        ret += (20.0 * Math.sin(6.0 * lng * pi) + 20.0 * Math.sin(2.0 * lng * pi)) * 2.0 / 3.0;
        ret += (20.0 * Math.sin(lng * pi) + 40.0 * Math.sin(lng / 3.0 * pi)) * 2.0 / 3.0;
        ret += (150.0 * Math.sin(lng / 12.0 * pi) + 300.0 * Math.sin(lng / 30.0 * pi)) * 2.0 / 3.0;
        return ret;
    }

    /**
     * 判断是否在国内,不在国内不做偏移
     *
     * @param lng
     * @param lat
     * @return
     */
    public static boolean out_of_china(double lng, double lat) {
        if (lng < 72.004 || lng > 137.8347) {
            return true;
        } else if (lat < 0.8293 || lat > 55.8271) {
            return true;
        }
        return false;
    }

}

4.DateUtil 日期加减工具类

public class DateUtil {

    private static final String dateFormat = "yyyy-MM-dd";

    /**
     * 格式化日期
     *
     * @param date
     * @return
     */
    public static String formatDate(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        return sdf.format(date);

    }

    /**
     * 在日期date上增加amount天 。
     *
     * @param date   处理的日期,非null
     * @param amount 要加的天数,可能为负数
     */
    public static Date addDays(Date date, int amount) {
        Calendar now =Calendar.getInstance();
        now.setTime(date);
        now.set(Calendar.DATE,now.get(Calendar.DATE)+amount);
        return now.getTime();
    }

    public static void main(String[] args) {
        System.out.println(DateUtil.formatDate(new Date()));
        System.out.println(DateUtil.formatDate(DateUtil.addDays(new Date(), -1)));
    }
}

5.EmailUtil email发送工具类

public class EmailUtil {

    private static Session session;
    private static String  user;

    private MimeMessage msg;
    private String      text;
    private String      html;
    private List<MimeBodyPart> attachments = new ArrayList<MimeBodyPart>();

    private EmailUtil() {
    }

    public static Properties defaultConfig(Boolean debug) {
        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.ssl.enable", "true");
        props.put("mail.debug", "false");
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.debug", null != debug ? debug.toString() : "false");
        props.put("mail.smtp.timeout", "10000");
        props.put("mail.smtp.port", "465");
        return props;
    }

    /**
     * smtp entnterprise qq
     *
     * @param debug
     * @return
     */
    public static Properties SMTP_ENT_QQ(boolean debug) {
        Properties props = defaultConfig(debug);
        props.put("mail.smtp.host", "smtp.exmail.qq.com");
        return props;
    }

    /**
     * smtp qq
     *
     * @param debug enable debug
     * @return
     */
    public static Properties SMTP_QQ(boolean debug) {
        Properties props = defaultConfig(debug);
        props.put("mail.smtp.host", "smtp.qq.com");
        return props;
    }

    /**
     * smtp 163
     *
     * @param debug enable debug
     * @return
     */
    public static Properties SMTP_163(Boolean debug) {
        Properties props = defaultConfig(debug);
        props.put("mail.smtp.host", "smtp.163.com");
        return props;
    }

    /**
     * config username and password
     *
     * @param props    email property config
     * @param username email auth username
     * @param password email auth password
     */
    public static void config(Properties props, final String username, final String password) {
        props.setProperty("username", username);
        props.setProperty("password", password);
        config(props);
    }

    public static void config(Properties props) {
        final String username = props.getProperty("username");
        final String password = props.getProperty("password");
        user = username;
        session = Session.getInstance(props, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });
    }

    /**
     * set email subject
     *
     * @param subject subject title
     * @return
     * @throws MessagingException
     */
    public static EmailUtil subject(String subject) throws MessagingException {
        EmailUtil emailUtil = new EmailUtil();
        emailUtil.msg = new MimeMessage(session);
        emailUtil.msg.setSubject(subject, "UTF-8");
        return emailUtil;
    }

    /**
     * set email from
     *
     * @param nickName from nickname
     * @return
     * @throws MessagingException
     */
    public EmailUtil from(String nickName) throws MessagingException {
        return from(nickName, user);
    }

    /**
     * set email nickname and from user
     *
     * @param nickName
     * @param from
     * @return
     * @throws MessagingException
     */
    public EmailUtil from(String nickName, String from) throws MessagingException {
        try {
            nickName = MimeUtility.encodeText(nickName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        msg.setFrom(new InternetAddress(nickName + " <" + from + ">"));
        return this;
    }

    public EmailUtil replyTo(String... replyTo) throws MessagingException {
        String result = Arrays.asList(replyTo).toString().replaceAll("(^\\[|\\]$)", "").replace(", ", ",");
        msg.setReplyTo(InternetAddress.parse(result));
        return this;
    }

    public EmailUtil replyTo(String replyTo) throws MessagingException {
        msg.setReplyTo(InternetAddress.parse(replyTo.replace(";", ",")));
        return this;
    }

    public EmailUtil to(String... to) throws Exception {
        return addRecipients(to, Message.RecipientType.TO);
    }

    public EmailUtil to(String to) throws MessagingException {
        return addRecipient(to, Message.RecipientType.TO);
    }

    public EmailUtil cc(String... cc) throws MessagingException {
        return addRecipients(cc, Message.RecipientType.CC);
    }

    public EmailUtil cc(String cc) throws MessagingException {
        return addRecipient(cc, Message.RecipientType.CC);
    }

    public EmailUtil bcc(String... bcc) throws MessagingException {
        return addRecipients(bcc, Message.RecipientType.BCC);
    }

    public EmailUtil bcc(String bcc) throws MessagingException {
        return addRecipient(bcc, Message.RecipientType.BCC);
    }

    private EmailUtil addRecipients(String[] recipients, Message.RecipientType type) throws MessagingException {
        String result = Arrays.asList(recipients).toString().replace("(^\\[|\\]$)", "").replace(", ", ",");
        msg.setRecipients(type, InternetAddress.parse(result));
        return this;
    }

    private EmailUtil addRecipient(String recipient, Message.RecipientType type) throws MessagingException {
        msg.setRecipients(type, InternetAddress.parse(recipient.replace(";", ",")));
        return this;
    }

    public EmailUtil text(String text) {
        this.text = text;
        return this;
    }

    public EmailUtil html(String html) {
        this.html = html;
        return this;
    }

    public EmailUtil attach(File file) throws MessagingException {
        attachments.add(createAttachment(file, null));
        return this;
    }

    public EmailUtil attach(File file, String fileName) throws MessagingException {
        attachments.add(createAttachment(file, fileName));
        return this;
    }

    private MimeBodyPart createAttachment(File file, String fileName) throws MessagingException {
        MimeBodyPart   attachmentPart = new MimeBodyPart();
        FileDataSource fds            = new FileDataSource(file);
        attachmentPart.setDataHandler(new DataHandler(fds));
        try {
            attachmentPart.setFileName(null == fileName ? MimeUtility.encodeText(fds.getName()) : MimeUtility.encodeText(fileName));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return attachmentPart;
    }

    public void send() throws MessagingException {
        if (text == null && html == null)
            throw new NullPointerException("At least one context has to be provided: Text or Html");

        MimeMultipart cover;
        boolean       usingAlternative = false;
        boolean       hasAttachments   = attachments.size() > 0;

        if (text != null && html == null) {
            // TEXT ONLY
            cover = new MimeMultipart("mixed");
            cover.addBodyPart(textPart());
        } else if (text == null && html != null) {
            // HTML ONLY
            cover = new MimeMultipart("mixed");
            cover.addBodyPart(htmlPart());
        } else {
            // HTML + TEXT
            cover = new MimeMultipart("alternative");
            cover.addBodyPart(textPart());
            cover.addBodyPart(htmlPart());
            usingAlternative = true;
        }

        MimeMultipart content = cover;
        if (usingAlternative && hasAttachments) {
            content = new MimeMultipart("mixed");
            content.addBodyPart(toBodyPart(cover));
        }

        for (MimeBodyPart attachment : attachments) {
            content.addBodyPart(attachment);
        }

        msg.setContent(content);
        msg.setSentDate(new Date());
        Transport.send(msg);
    }

    private MimeBodyPart toBodyPart(MimeMultipart cover) throws MessagingException {
        MimeBodyPart wrap = new MimeBodyPart();
        wrap.setContent(cover);
        return wrap;
    }

    private MimeBodyPart textPart() throws MessagingException {
        MimeBodyPart bodyPart = new MimeBodyPart();
        bodyPart.setText(text);
        return bodyPart;
    }

    private MimeBodyPart htmlPart() throws MessagingException {
        MimeBodyPart bodyPart = new MimeBodyPart();
        bodyPart.setContent(html, "text/html; charset=utf-8");
        return bodyPart;
    }

}

6.EncodeDecodeUtil 加密工具类

public class EncodeDecodeUtil {

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

    private static final String DEFAULT_CHARSET = "utf-8";


    /**
     * 对字符串进行MD5加密
     * @param str 待加密字符串
     * @return 加密后的字符串
     */
    public static String encodeWithMD5(String str) {
        return encode("MD5", str);
    }

    /**
     * 对字符串进行SHA1加密
     * @param str 待加密字符串
     * @return 加密后的字符串
     */
    public static String encodeWithSHA1(String str) {
        return encode("SHA1", str);
    }

    /**
     * 对字符串进行SHA-256加密
     * @param str 待加密字符串
     * @return 加密后的字符串
     */
    public static String encodeWithSHA256(String str) {
        return encode("SHA-256", str);
    }

    /**
     * 通过加密算法加密字符串
     */
    public static String encode(String algorithm, String str) {
        if (str == null) {
            return null;
        }
        try {
            MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
            messageDigest.update(str.getBytes());
            return getFormattedText(messageDigest.digest());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    public static String encodeBase64(String str) {
        if (StringUtils.isBlank(str)) {
            return null;
        }
        try {
            return Base64.getEncoder().encodeToString(str.getBytes(DEFAULT_CHARSET));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static String decodeBase64(String str) {
        if (StringUtils.isBlank(str)) {
            return null;
        }
        try {
            byte[] bytes = Base64.getDecoder().decode(str);
            return new String(bytes, DEFAULT_CHARSET);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static String decodeUrl(String str) {
        if (StringUtils.isBlank(str)) {
            return null;
        }
        try {
            return java.net.URLDecoder.decode(str, "UTF-8");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static String encodeUrl(String str) {
        if (StringUtils.isBlank(str)) {
            return null;
        }
        try {
            return java.net.URLEncoder.encode(str, "UTF-8");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static String getFormattedText(byte[] bytes) {
        int len = bytes.length;
        StringBuilder buf = new StringBuilder(len * 2);
        // 把密文转换成十六进制的字符串形式
        for (int j = 0; j < len; j++) {
            buf.append(HEX[(bytes[j] >> 4) & 0x0f]);
            buf.append(HEX[bytes[j] & 0x0f]);
        }
        return buf.toString();
    }

}

7.GzipUtil 压缩工具类

public class GzipUtil {

    private static Logger logger = LoggerFactory.getLogger(GZIPUtil.class);
    public static final String GZIP_ENCODE_UTF_8 = "UTF-8";

    /**
     * 字符串压缩为GZIP字节数组
     *
     * @param str
     * @return
     */
    public static byte[] compress(String str) {
        return compress(str, GZIP_ENCODE_UTF_8);
    }

    /**
     * 字符串压缩为GZIP字节数组
     *
     * @param str
     * @param encoding
     * @return
     */
    public static byte[] compress(String str, String encoding) {
        if (str == null || str.length() == 0) {
            return null;
        }
        byte[] bytes = null;
        try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            GZIPOutputStream gzip;
            try {
                gzip = new GZIPOutputStream(out);
                gzip.write(str.getBytes(encoding));
                gzip.close();
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }
            bytes = out.toByteArray();
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }

        return bytes;
    }

    public static byte[] compress(byte[] bytes) {
        if (bytes == null || bytes.length == 0) {
            return null;
        }
        byte[] byteArr = null;
        try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            GZIPOutputStream gzip = null;
            try {
                gzip = new GZIPOutputStream(out);
                gzip.write(bytes);

            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }finally {
            	if(gzip!=null){
            		 gzip.close();
            	}
    		}
            byteArr = out.toByteArray();
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
        return byteArr;
    }

    /**
     * GZIP解压缩
     *
     * @param bytes
     * @return
     */
    public static byte[] uncompress(byte[] bytes) {
        if (bytes == null || bytes.length == 0) {
            return null;
        }
        byte[] byteArr = null;
        try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            ByteArrayInputStream in = new ByteArrayInputStream(bytes);
            GZIPInputStream ungzip = new GZIPInputStream(in);
            try {
                byte[] buffer = new byte[256];
                int n;
                while ((n = ungzip.read(buffer)) >= 0) {
                    out.write(buffer, 0, n);
                }
                in.close();

            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }finally {
            	  ungzip.close();
			}
            byteArr = out.toByteArray();
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
        return byteArr;
    }

    /**
     * @param bytes
     * @return
     */
    public static String uncompress2Str(byte[] bytes) {
        return uncompress2Str(bytes, GZIP_ENCODE_UTF_8);
    }

    /**
     * @param bytes
     * @param encoding
     * @return
     */
    public static String uncompress2Str(byte[] bytes, String encoding) {
        if (bytes == null || bytes.length == 0) {
            return null;
        }
        String str = null;
        try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            ByteArrayInputStream in = new ByteArrayInputStream(bytes);
            try {
                GZIPInputStream ungzip = new GZIPInputStream(in);
                byte[] buffer = new byte[256];
                int n;
                while ((n = ungzip.read(buffer)) >= 0) {
                    out.write(buffer, 0, n);
                }
                in.close();
                ungzip.close();
                str = out.toString(encoding);
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
        return str;
    }
}

8.HttpClient http远程调用工具类

//远程调用工具类
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.ParseException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class HttpClient {
	private String url;
	private Map<String, String> param;
	private int statusCode;
	private String content;
	private String xmlParam;
	private boolean isHttps;

	public boolean isHttps() {
		return isHttps;
	}

	public void setHttps(boolean isHttps) {
		this.isHttps = isHttps;
	}

	public String getXmlParam() {
		return xmlParam;
	}

	public void setXmlParam(String xmlParam) {
		this.xmlParam = xmlParam;
	}

	public HttpClient(String url, Map<String, String> param) {
		this.url = url;
		this.param = param;
	}

	public HttpClient(String url) {
		this.url = url;
	}

	public void setParameter(Map<String, String> map) {
		param = map;
	}

	public void addParameter(String key, String value) {
		if (param == null)
			param = new HashMap<String, String>();
		param.put(key, value);
	}

	public void post() throws ClientProtocolException, IOException {
		HttpPost http = new HttpPost(url);
		setEntity(http);
		execute(http);
	}

	public void put() throws ClientProtocolException, IOException {
		HttpPut http = new HttpPut(url);
		setEntity(http);
		execute(http);
	}

	public void get() throws ClientProtocolException, IOException {
		if (param != null) {
			StringBuilder url = new StringBuilder(this.url);
			boolean isFirst = true;
			for (String key : param.keySet()) {
				if (isFirst)
					url.append("?");
				else
					url.append("&");
				url.append(key).append("=").append(param.get(key));
			}
			this.url = url.toString();
		}
		HttpGet http = new HttpGet(url);
		execute(http);
	}

	/**
	 * set http post,put param
	 */
	private void setEntity(HttpEntityEnclosingRequestBase http) {
		if (param != null) {
			List<NameValuePair> nvps = new LinkedList<NameValuePair>();
			for (String key : param.keySet())
				nvps.add(new BasicNameValuePair(key, param.get(key))); // 参数
			http.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8)); // 设置参数
		}
		if (xmlParam != null) {
			http.setEntity(new StringEntity(xmlParam, Consts.UTF_8));
		}
	}

	private void execute(HttpUriRequest http) throws ClientProtocolException,
			IOException {
		CloseableHttpClient httpClient = null;
		try {
			if (isHttps) {
				SSLContext sslContext = new SSLContextBuilder()
						.loadTrustMaterial(null, new TrustStrategy() {
							// 信任所有
							public boolean isTrusted(X509Certificate[] chain,
									String authType)
									throws CertificateException {
								return true;
							}
						}).build();
				SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
						sslContext);
				httpClient = HttpClients.custom().setSSLSocketFactory(sslsf)
						.build();
			} else {
				httpClient = HttpClients.createDefault();
			}
			CloseableHttpResponse response = httpClient.execute(http);
			try {
				if (response != null) {
					if (response.getStatusLine() != null)
						statusCode = response.getStatusLine().getStatusCode();
					HttpEntity entity = response.getEntity();
					// 响应内容
					content = EntityUtils.toString(entity, Consts.UTF_8);
				}
			} finally {
				response.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			httpClient.close();
		}
	}

	public int getStatusCode() {
		return statusCode;
	}

	public String getContent() throws ParseException, IOException {
		return content;
	}

}

9.JwtUtil jwt工具类

public class JwtUtils {
    public static final long EXPIRATION = 1000 * 60 * 60 * 24;
    public static final String SECRET = "ukc8BDbRigUDaY6pZFfWus2jZWLPHO";

    /**
     * 根据用户id和nickname生成一个token
     * @param id
     * @param nickname
     * @return
     */
    public static String getToken(String id, String nickname) {
        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                .setSubject("online-encourage")
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION))
                .claim("id", id)
                .claim("nickname", nickname)
                .signWith(SignatureAlgorithm.HS256, SECRET)
                .compact();
    }

    /**
     * 判断token是否过期
     * @param token
     * @return
     */
    public static boolean isExpiration(String token) {
        if (StringUtils.isEmpty(token)) {
            return false;
        }
        Date expiration = getClaimByToken(token).getExpiration();
        return expiration.before(new Date());
    }

    /**
     * 解析token
     * @param token
     * @return
     */
    public static Claims getClaimByToken(String token) {
        return Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token).getBody();
    }

    /**
     * 获取token并解析--得到用户id
     * @param request
     * @return
     */
    public static String getUserIdByToken(HttpServletRequest request) {
        String token = request.getHeader("token");
        System.out.println("token为:--->>>>>>>>>>>>>>"+token);
        if (StringUtils.isEmpty(token)) {
            return "";
        }
        return (String) getClaimByToken(token).get("id");
    }
}

10.LanguageUtil 语种工具类

public class LanguageUtil {


    /**
     * 是否只有数字
     */
    public static boolean isNumeric(String str) {
        return str != null && str.length() > 0 && Pattern.matches("[0-9]*", str);
    }

    /**
     * 是否只有字母
     */
    public static boolean isOnlyLetter(String str) {
        return str != null && str.length() > 0 && Pattern.matches("^[A-Za-z]+$", str);
    }

    /**
     * 是否只有字母和空格
     */
    public static boolean isLetter(String str) {
        return str != null && str.length() > 0 && Pattern.matches("^[A-Za-z\\u0020]+$", str);
    }

    /**
     * 是否只有汉字和空格
     */
    public static boolean isChinese(String str) {
        return str != null && str.length() > 0 && Pattern.matches("^[\\u4e00-\\u9fa5\\u0020]+$", str);
    }

    /**
     * 是否只有英文和数字
     */
    public static boolean isLetterAndNumber(String str) {
        return str != null && str.length() > 0 && Pattern.matches("^[0-9A-Za-z\\u0020]+$", str);
    }

    /**
     * 是否只有中文和数字
     */
    public static boolean isChineseAndNumber(String str) {
        return str != null && str.length() > 0 && Pattern.matches("^[0-9\\u4e00-\\u9fa5\\u0020]+$", str);
    }

    /**
     * 是否只有韩文和数字
     */
    public static boolean isKoreanAndNumber(String str) {
        return str != null && str.length() > 0 && Pattern.matches("^[0-9\\uac00-\\ud7a3\\u0020]+$", str);
    }

    /**
     * 是否只有日文和数字
     */
    public static boolean isJapanAndNumber(String str) {
        return str != null && str.length() > 0 && Pattern.matches("^[0-9\\u0800-\\u4e00\\u0020]+$", str);
    }

}

11.MD5 MD5加密工具类

public final class MD5 {

    public static String encrypt(String strSrc) {
        try {
            char hexChars[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
                    '9', 'a', 'b', 'c', 'd', 'e', 'f' };
            byte[] bytes = strSrc.getBytes();
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(bytes);
            bytes = md.digest();
            int j = bytes.length;
            char[] chars = new char[j * 2];
            int k = 0;
            for (int i = 0; i < bytes.length; i++) {
                byte b = bytes[i];
                chars[k++] = hexChars[b >>> 4 & 0xf];
                chars[k++] = hexChars[b & 0xf];
            }
            return new String(chars);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            throw new RuntimeException("MD5加密出错!!+" + e);
        }
    }

}

12.ObjectDeepCopyUtil 对象深度拷贝工具类

public class ObjectDeepCopyUtil {

    /**
     * 单个对象的深拷贝,srcObj对应的需实现java.io.Serializable接口
     * @param srcObj obj
     * @return new  obj
     */
    public static Object depthClone(Object srcObj) {
        Object cloneObj = null;
        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ObjectOutputStream oo = new ObjectOutputStream(out);
            oo.writeObject(srcObj);
            ByteArrayInputStream in = new ByteArrayInputStream(
                    out.toByteArray());
            ObjectInputStream oi = new ObjectInputStream(in);
            cloneObj = oi.readObject();
        } catch (Exception ex) {
            return null;
        }
        return cloneObj;
    }

    /**
     * 多个对象的深拷贝,srcObj对应的需实现java.io.Serializable接口
     * @param list obj
     * @return new list obj
     */
    public static <T> List<T> listDepthClone(List<T> list) {
        List<T> newList = new ArrayList<>();
        for (Object item : list) {
            if (item == null) {
                continue;
            }
            Object val = depthClone(item);
            if (val != null) {
                newList.add((T) val);
            }
        }
        return newList;
    }

}

13.OrderNoUtil 订单号工具类

public class OrderNoUtil {

    /**日期+随机数拼接 ---保证订单号唯一
     * 获取订单号
     * @return
     */
    public static String getOrderNo() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String newDate = sdf.format(new Date());
        String result = "";
        Random random = new Random();
        for (int i = 0; i < 3; i++) {
            result += random.nextInt(10);
        }
        return newDate + result;
    }

}

14.PoolPrintUtil 线程池打印工具类

public class PoolPrintUtil {

    /**
     * 打印线程池状态
     * @param executor 线程池
     * @param logger logger
     */
    public void printThreadPoolStatus(ThreadPoolExecutor executor, Logger logger) {
        int poolSize = executor.getPoolSize();
        int corePoolSize = executor.getCorePoolSize();
        int activeCount = executor.getActiveCount();
        long completedTaskCount = executor.getCompletedTaskCount();
        long taskCount = executor.getTaskCount();
        int queueCount = executor.getQueue().size();
        int largestPoolSize = executor.getLargestPoolSize();
        int maximumPoolSize = executor.getMaximumPoolSize();
        long time = executor.getKeepAliveTime(TimeUnit.MILLISECONDS);
        boolean isShutDown = executor.isShutdown();
        boolean isTerminated = executor.isTerminated();

        String info = String.format("初始线程数:%s、核心线程数:%s、正在执行的任务数量:%s、已完成任务数量:%s、任务总数:%s、" +
                "队列里缓存的任务数量:%s、池中存在的最大线程数:%s、最大允许的线程数:%s、线程空闲时间:%s、线程池是否关闭:%s、" +
                "线程池是否终止:%s", poolSize, corePoolSize, activeCount, completedTaskCount, taskCount, queueCount,
                largestPoolSize, maximumPoolSize, time, isShutDown, isTerminated);
        logger.info(info);
    }

    public void printThreadPoolStatus(Logger logger, ThreadPoolExecutor... executors) {
        for (int i=0; i< executors.length; i++) {
            printThreadPoolStatus(executors[i], logger);
        }
    }

}

15.RandomUtil 手机验证码生成工具类

//用于生成四位或者六位随机数,多用于验证码
public class RandomUtil {

    private static final Random random = new Random();

    private static final DecimalFormat fourdf = new DecimalFormat("0000");

    private static final DecimalFormat sixdf = new DecimalFormat("000000");

    public static String getFourBitRandom() {
        return fourdf.format(random.nextInt(10000));
    }

    public static String getSixBitRandom() {
        return sixdf.format(random.nextInt(1000000));
    }

    /**
     * 给定数组,抽取n个数据
     *
     * @param list
     * @param n
     * @return
     */
    public static ArrayList getRandom(List list, int n) {

        Random random = new Random();
        HashMap<Object, Object> hashMap = new HashMap<Object, Object>();
        // 生成随机数字并存入HashMap
        for (int i = 0; i < list.size(); i++) {
            int number = random.nextInt(100) + 1;
            hashMap.put(number, i);
        }
        // 从HashMap导入数组
        Object[] robjs = hashMap.values().toArray();
        ArrayList r = new ArrayList();
        // 遍历数组并打印数据
        for (int i = 0; i < n; i++) {
            r.add(list.get((int) robjs[i]));
            System.out.print(list.get((int) robjs[i]) + "\t");
        }
        System.out.print("\n");
        return r;
    }
}

16.ResponseEntity 统一结果返回类

@Data
@Accessors(chain = true)
@ApiModel(value = "统一结果返回类")
public class ResponseEntity {
    @ApiModelProperty(value = "是否成功")
    private Boolean success;

    @ApiModelProperty(value = "状态码")
    private Integer code;

    @ApiModelProperty(value = "返回消息")
    private String msg;

    @ApiModelProperty(value = "返回数据")
    private Map<String, Object> data = new HashMap<>();

    private ResponseEntity() {}

    public static ResponseEntity ok() {
        return new ResponseEntity()
                .setSuccess(true)
                .setCode(ResultCode.SUCCESS_CODE)
                .setMsg("成功");
    }

    public static ResponseEntity error() {
        return new ResponseEntity()
                .setSuccess(false)
                .setCode(ResultCode.FAIL_CODE)
                .setMsg("失败");
    }

//    链式编程
    public ResponseEntity success(Boolean success) {
        this.setSuccess(success);
        return this;
    }
    public ResponseEntity code(Integer code) {
        this.setCode(code);
        return this;
    }
    public ResponseEntity msg(String msg) {
        this.setMsg(msg);
        return this;
    }
    public ResponseEntity data(String key, Object val) {
        this.data.put(key, val);
        return this;
    }
}

17.ResponseUtil 结果响应工具类

public class ResponseUtil {

    public static void out(HttpServletResponse response, ResponseEntity r) {
        ObjectMapper mapper = new ObjectMapper();
        response.setStatus(HttpStatus.OK.value());
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        try {
            mapper.writeValue(response.getWriter(), r);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

18.XmlUtil xml转换map工具类

public class XmlUtils {
	/**
	 * 将xml string 转化为map
	 * 
	 * @param xmlDoc
	 * @return
	 * @throws IOException
	 * @throws JDOMException
	 */
	@SuppressWarnings("unchecked")
	public static Map<String, Object> xmlToMap(String xmlDoc) throws JDOMException, IOException {
		// 创建一个新的字符串
		StringReader read = new StringReader(xmlDoc);
		// 创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
		InputSource source = new InputSource(read);
		// 创建一个新的SAXBuilder
		SAXBuilder sb = new SAXBuilder();

		Map<String, Object> xmlMap = new HashMap<String, Object>();

		Document doc = sb.build(source); // 通过输入源构造一个Document
		Element root = doc.getRootElement(); // 取的根元素

		List<Element> cNodes = root.getChildren(); // 得到根元素所有子元素的集合(根元素的子节点,不包括孙子节点)
		Element et = null;
		for (int i = 0; i < cNodes.size(); i++) {
			et = (Element) cNodes.get(i); // 循环依次得到子元素
			xmlMap.put(et.getName(), et.getText());
		}
		return xmlMap;
	}

	/**
	 * 将xml string 转化为map
	 *
	 * @param xmlDoc
	 * @return
	 * @throws IOException
	 * @throws JDOMException
	 */
	@SuppressWarnings("unchecked")
	public static Map<String, Object> secondLevelXmlToMap(String xmlDoc) throws JDOMException, IOException {
		// 创建一个新的字符串
		StringReader read = new StringReader(xmlDoc);
		// 创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
		InputSource source = new InputSource(read);
		// 创建一个新的SAXBuilder
		SAXBuilder sb = new SAXBuilder();

		Map<String, Object> xmlMap = new HashMap<String, Object>();

		Document doc = sb.build(source); // 通过输入源构造一个Document
		Element root = doc.getRootElement(); // 取的根元素

		List<Element> cNodes = root.getChildren(); // 得到根元素所有子元素的集合(根元素的子节点,不包括孙子节点)
		Element et = null;
		for (int i = 0; i < cNodes.size(); i++) {
			et = (Element) cNodes.get(i); // 循环依次得到子元素
			List<Element> etChildrens = et.getChildren();
			for (int j = 0 ; j < etChildrens.size() ; j++){
				Element ChildrenEt = (Element) etChildrens.get(j); // 循环依次得到子元素
				xmlMap.put(ChildrenEt.getName(), ChildrenEt.getText());
			}
		}
		return xmlMap;
	}
}
  Java知识库 最新文章
计算距离春节还有多长时间
系统开发系列 之WebService(spring框架+ma
springBoot+Cache(自定义有效时间配置)
SpringBoot整合mybatis实现增删改查、分页查
spring教程
SpringBoot+Vue实现美食交流网站的设计与实
虚拟机内存结构以及虚拟机中销毁和新建对象
SpringMVC---原理
小李同学: Java如何按多个字段分组
打印票据--java
上一篇文章      下一篇文章      查看所有文章
加:2021-09-06 11:02:26  更:2021-09-06 11:04:21 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/23 13:04:05-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码