热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

使用MavenJAR插件将单个或多个文件及其依赖项合并为一个可引用的JAR包

本文介绍了如何利用Maven中的maven-assembly-plugin插件将单个或多个Java文件及其依赖项打包成一个可引用的JAR文件。首先,需要创建一个新的Maven项目,并将待打包的Java文件复制到该项目中。通过配置maven-assembly-plugin,可以实现将所有文件及其依赖项合并为一个独立的JAR包,方便在其他项目中引用和使用。此外,该方法还支持自定义装配描述符,以满足不同场景下的需求。

本次本篇使用的工具是Maven中的

maven-assembly-plugin

插件。

======================================================================================================

1.首先,需要新建一个maven项目,将单个或多个java文件拷贝到本项目中

例如,下面这个QR_Code.java文件

【Maven jar】打包单个或多个文件,有依赖jar包的将包一起打包成一个jar包供别的项目引用
【Maven jar】打包单个或多个文件,有依赖jar包的将包一起打包成一个jar包供别的项目引用
package com.sxd.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import com.google.zxing.*;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

/**
 * 二维码工具类
 * @author SXD
 * @Date 2018.2.1
 *
 */
public class QR_Code {
    private static int BLACK = 0x000000;
    private static int WHITE = 0xFFFFFF;

    /**
     * 内部类,设置二维码相关参数
     */
    @Data(staticCOnstructor= "of")
    @NoArgsConstructor
    @AllArgsConstructor
    @Accessors(chain = true)
    public  class CodeModel {
        /**
         * 正文
         */
        private String contents;
        /**
         * 二维码宽度
         */
        private int width = 400;
        /**
         * 二维码高度
         */
        private int height = 400;
        /**
         * 图片格式
         */
        private String format = "png";
        /**
         * 编码方式
         */
        private String character_set = "utf-8";
        /**
         * 字体大小
         */
        private int fOntSize= 12;
        /**
         * logo
         */
        private File logoFile;
        /**
         * logo所占二维码比例
         */
        private float logoRatio = 0.20f;
        /**
         * 二维码下文字
         */
        private String desc;
        private int whiteWidth;//白边的宽度
        private int[] bottomStart;//二维码最下边的开始坐标
        private int[] bottomEnd;//二维码最下边的结束坐标
    }


    /**
     * 1.创建最原始的二维码图片
     * @param info
     * @return
     */
    private BufferedImage createCodeImage(CodeModel info){

        String cOntents= info.getContents() == null || "".equals(info.getContents())  ? "暂无内容" : info.getContents();//获取正文
        int width = info.getWidth();//宽度
        int height = info.getHeight();//高度
        Map hint = new HashMap();
        hint.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);//设置二维码的纠错级别【级别分别为M L H Q ,H纠错能力级别最高,约可纠错30%的数据码字】
        hint.put(EncodeHintType.CHARACTER_SET, info.getCharacter_set());//设置二维码编码方式【UTF-8】
        hint.put(EncodeHintType.MARGIN, 0);

        MultiFormatWriter writer = new MultiFormatWriter();
        BufferedImage img = null;
        try {
            //构建二维码图片
            //QR_CODE 一种矩阵二维码
            BitMatrix bm = writer.encode(contents, BarcodeFormat.QR_CODE, width, height, hint);
            int[] locatiOnTopLeft= bm.getTopLeftOnBit();
            int[] locatiOnBottomRight= bm.getBottomRightOnBit();
            info.setBottomStart(new int[]{locationTopLeft[0], locationBottomRight[1]});
            info.setBottomEnd(locationBottomRight);
            int w = bm.getWidth();
            int h = bm.getHeight();
            img = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
            for(int x=0;x0){
                    logoWidth = logoWidth>width*ratio ? (int)(width*ratio) : logoWidth;
                    logoHeight = logoHeight>height*ratio ? (int)(height*ratio) : logoHeight;
                }
                int x = (width-logoWidth)/2;
                int y = (height-logoHeight)/2;
                //根据logo 起始位置 和 宽高 在二维码图片上画出logo
                g.drawImage(logoImg, x, y, logoWidth, logoHeight, null);
            }catch(Exception e){
                e.printStackTrace();
            }
        }

        //处理二维码下文字
        String desc = info.getDesc();
        if(!(desc == null || "".equals(desc))){
            try{
                //设置文字字体
                int whiteWidth = info.getHeight()-info.getBottomEnd()[1];
                Font fOnt= new Font("黑体", Font.BOLD, info.getFontSize());
                int fOntHeight= g.getFontMetrics(font).getHeight();
                //计算需要多少行
                int lineNum = 1;
                int currentLineLen = 0;
                for(int i=0;iwidth){
                        lineNum++;
                        currentLineLen = 0;
                        continue;
                    }
                    currentLineLen += charWidth;
                }
                int totalFOntHeight= fontHeight*lineNum;
                int wordTopMargin = 4;
                BufferedImage bm1 = new BufferedImage(width, height+totalFontHeight+wordTopMargin-whiteWidth, BufferedImage.TYPE_INT_RGB);
                Graphics g1 = bm1.getGraphics();
                if(totalFontHeight+wordTopMargin-whiteWidth>0){
                    g1.setColor(Color.WHITE);
                    g1.fillRect(0, height, width, totalFontHeight+wordTopMargin-whiteWidth);
                }
                g1.setColor(new Color(BLACK));
                g1.setFont(font);
                g1.drawImage(bm, 0, 0, null);
                width = info.getBottomEnd()[0]-info.getBottomStart()[0];
                height = info.getBottomEnd()[1]+1;
                currentLineLen = 0;
                int currentLineIndex = 0;
                int baseLo = g1.getFontMetrics().getAscent();
                for(int i=0;iwidth){
                        currentLineIndex++;
                        currentLineLen = 0;
                        g1.drawString(c, currentLineLen + whiteWidth, height+baseLo+fontHeight*(currentLineIndex)+wordTopMargin);
                        currentLineLen = charWidth;
                        continue;
                    }
                    g1.drawString(c, currentLineLen+whiteWidth, height+baseLo+fontHeight*(currentLineIndex) + wordTopMargin);
                    currentLineLen += charWidth;
                }
                g1.dispose();
                bm = bm1;
            }catch(Exception e){
                e.printStackTrace();
            }
        }

        try{
            ImageIO.write(bm, (info.getFormat() == null || "".equals(info.getFormat())) ? info.getFormat() : info.getFormat(), output);
        }catch(Exception e){
            e.printStackTrace();
        }
    }


    /**
     * 3.创建 带logo和文字的二维码
     * @param info
     * @param file
     */
    public void createCodeImage(CodeModel info, File file){
        File parent = file.getParentFile();
        if(!parent.exists())parent.mkdirs();
        OutputStream output = null;
        try{
            output = new BufferedOutputStream(new FileOutputStream(file));
            dealLogoAndDesc(info, output);
            output.flush();
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            try {
                output.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 3.创建  带logo和文字的二维码
     * @param info
     * @param filePath
     */
    public void createCodeImage(CodeModel info, String filePath){
        createCodeImage(info, new File(filePath));
    }

    /**
     * 4.创建  带logo和文字的二维码
     * @param filePath
     */
    public void createCodeImage(String contents,String filePath){
        CodeModel codeModel = new CodeModel();
        codeModel.setContents(contents);
        createCodeImage(codeModel, new File(filePath));
    }


    /**
     * 5.读取 二维码 获取二维码中正文
     * @param input
     * @return
     */
    public String decode(InputStream input){
        Map hint = new HashMap();
        hint.put(DecodeHintType.POSSIBLE_FORMATS, BarcodeFormat.QR_CODE);
        String result = "";
        try{
            BufferedImage img = ImageIO.read(input);
            int[] pixels = img.getRGB(0, 0, img.getWidth(), img.getHeight(), null, 0, img.getWidth());
            LuminanceSource source = new RGBLuminanceSource(img.getWidth(), img.getHeight(), pixels);
            BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
            QRCodeReader reader = new QRCodeReader();
            Result r = reader.decode(bitmap, hint);
            result = r.getText();
        }catch(Exception e){
            result="读取错误";
        }
        return result;
    }



}
【Maven jar】打包单个或多个文件,有依赖jar包的将包一起打包成一个jar包供别的项目引用

推荐阅读
  • 本文将介绍如何编写一些有趣的VBScript脚本,这些脚本可以在朋友之间进行无害的恶作剧。通过简单的代码示例,帮助您了解VBScript的基本语法和功能。 ... [详细]
  • python的交互模式怎么输出名文汉字[python常见问题]
    在命令行模式下敲命令python,就看到类似如下的一堆文本输出,然后就进入到Python交互模式,它的提示符是>>>,此时我们可以使用print() ... [详细]
  • Struts与Spring框架的集成指南
    本文详细介绍了如何将Struts和Spring两个流行的Java Web开发框架进行整合,涵盖从环境配置到代码实现的具体步骤。 ... [详细]
  • 本文详细探讨了Java中的ClassLoader类加载器的工作原理,包括其如何将class文件加载至JVM中,以及JVM启动时的动态加载策略。文章还介绍了JVM内置的三种类加载器及其工作方式,并解释了类加载器的继承关系和双亲委托机制。 ... [详细]
  • Logback使用小结
    1一定要使用slf4j的jar包,不要使用apachecommons的jar。否则滚动生成文件不生效,不滚动的时候却生效~~importorg.slf ... [详细]
  • PyCharm中配置Pylint静态代码分析工具
    本文详细介绍如何在PyCharm中配置和使用Pylint,帮助开发者进行静态代码检查,确保代码符合PEP8规范,提高代码质量。 ... [详细]
  • Explore a common issue encountered when implementing an OAuth 1.0a API, specifically the inability to encode null objects and how to resolve it. ... [详细]
  • 本文详细介绍如何使用Python进行配置文件的读写操作,涵盖常见的配置文件格式(如INI、JSON、TOML和YAML),并提供具体的代码示例。 ... [详细]
  • 技术分享:从动态网站提取站点密钥的解决方案
    本文探讨了如何从动态网站中提取站点密钥,特别是针对验证码(reCAPTCHA)的处理方法。通过结合Selenium和requests库,提供了详细的代码示例和优化建议。 ... [详细]
  • 本文详细介绍了如何在Linux系统上安装和配置Smokeping,以实现对网络链路质量的实时监控。通过详细的步骤和必要的依赖包安装,确保用户能够顺利完成部署并优化其网络性能监控。 ... [详细]
  • 本文详细探讨了Java中的24种设计模式及其应用,并介绍了七大面向对象设计原则。通过创建型、结构型和行为型模式的分类,帮助开发者更好地理解和应用这些模式,提升代码质量和可维护性。 ... [详细]
  • 深入理解 SQL 视图、存储过程与事务
    本文详细介绍了SQL中的视图、存储过程和事务的概念及应用。视图为用户提供了一种灵活的数据查询方式,存储过程则封装了复杂的SQL逻辑,而事务确保了数据库操作的完整性和一致性。 ... [详细]
  • 本文详细介绍了 Dockerfile 的编写方法及其在网络配置中的应用,涵盖基础指令、镜像构建与发布流程,并深入探讨了 Docker 的默认网络、容器互联及自定义网络的实现。 ... [详细]
  • 本文详细介绍了如何使用 Yii2 的 GridView 组件在列表页面实现数据的直接编辑功能。通过具体的代码示例和步骤,帮助开发者快速掌握这一实用技巧。 ... [详细]
  • 本文详细介绍了 Flink 和 YARN 的交互机制。YARN 是 Hadoop 生态系统中的资源管理组件,类似于 Spark on YARN 的配置方式。我们将基于官方文档,深入探讨如何在 YARN 上部署和运行 Flink 任务。 ... [详细]
author-avatar
终结者
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有