java二維碼生成導出成壓縮包

效果:

首先引入zxing依賴:

<lombok.version>1.18.8</lombok.version>
<zxing.version>3.3.3</zxing.version>

<!--lombok插件-->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>${lombok.version}</version>
    <scope>provided</scope>
</dependency>


<!-- 條形碼、二維碼生成 -->
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>core</artifactId>
    <version>${zxing.version}</version>
</dependency>
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>javase</artifactId>
    <version>${zxing.version}</version>
</dependency>

 

操作圖片的工具類:

import com.google.zxing.LuminanceSource;

import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;

/**
 *  
 *  * @projectName xx
 *  * @title     BufferedImageLuminanceSource   
 *  * @package    com.xx.common.utils  
 *  * @description    圖片工具  
 *  * @author IT_CREAT     
 *  * @date  2019 2019/11/5 14:22  
 *  * @version V1.0.0 
 *  
 */
public class BufferedImageLuminanceSource extends LuminanceSource {

    private final BufferedImage image;
    private final int left;
    private final int top;

    public BufferedImageLuminanceSource(BufferedImage image) {
        this(image, 0, 0, image.getWidth(), image.getHeight());
    }

    /**
     * 構造方法
     * @param image
     * @param left
     * @param top
     * @param width
     * @param height
     */
    public BufferedImageLuminanceSource(BufferedImage image, int left, int top, int width, int height) {
        super(width, height);

        int sourceWidth = image.getWidth();
        int sourceHeight = image.getHeight();
        if (left + width > sourceWidth || top + height > sourceHeight) {
            throw new IllegalArgumentException("Crop rectangle does not fit within image data.");
        }

        for (int y = top; y < top + height; y++) {
            for (int x = left; x < left + width; x++) {
                if ((image.getRGB(x, y) & 0xFF000000) == 0) {
                    image.setRGB(x, y, 0xFFFFFFFF); // = white
                }
            }
        }
        this.image = new BufferedImage(sourceWidth, sourceHeight, BufferedImage.TYPE_BYTE_GRAY);
        this.image.getGraphics().drawImage(image, 0, 0, null);
        this.left = left;
        this.top = top;
    }

    @Override
    public byte[] getRow(int y, byte[] row) {//從底層平臺的位圖提取一行(only one row)的亮度數據值
        if (y < 0 || y >= getHeight()) {
            throw new IllegalArgumentException("Requested row is outside the image: " + y);
        }
        int width = getWidth();
        if (row == null || row.length < width) {
            row = new byte[width];
        }
        image.getRaster().getDataElements(left, top + y, width, 1, row);
        return row;
    }

    @Override
    public byte[] getMatrix() {///從底層平臺的位圖提取亮度數據值
        int width = getWidth();
        int height = getHeight();
        int area = width * height;
        byte[] matrix = new byte[area];
        image.getRaster().getDataElements(left, top, width, height, matrix);
        return matrix;
    }

    @Override
    public boolean isCropSupported() {//是否支持裁剪
        return true;
    }

    /**
     * 返回一個新的對象與裁剪的圖像數據。實現可以保存對原始數據的引用,而不是複製。
     */
    @Override
    public LuminanceSource crop(int left, int top, int width, int height) {
        return new BufferedImageLuminanceSource(image, this.left + left, this.top + top, width, height);
    }

    @Override
    public boolean isRotateSupported() {//是否支持旋轉
        return true;
    }

    @Override
    public LuminanceSource rotateCounterClockwise() {//逆時針旋轉圖像數據的90度,返回一個新的對象。
        int sourceWidth = image.getWidth();
        int sourceHeight = image.getHeight();
        AffineTransform transform = new AffineTransform(0.0, -1.0, 1.0, 0.0, 0.0, sourceWidth);
        BufferedImage rotatedImage = new BufferedImage(sourceHeight, sourceWidth, BufferedImage.TYPE_BYTE_GRAY);
        Graphics2D g = rotatedImage.createGraphics();
        g.drawImage(image, transform, null);
        g.dispose();
        int width = getWidth();
        return new BufferedImageLuminanceSource(rotatedImage, top, sourceWidth - (left + width), getHeight(), width);
    }

}

zip壓縮工具類:

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import org.springframework.util.CollectionUtils;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 *  
 *  * @projectName xx
 *  * @title     ZipUtil   
 *  * @package    com.xx.common.utils  
 *  * @description    壓縮文件
 *  * @author IT_CREAT     
 *  * @date  2019 2019/9/30 1:41  
 *  * @version V1.0.0 
 *  
 */
public class ZipUtil {

    /**
     * 將一系列文件壓縮進zip文件
     * @param fileName zip文件的名稱,不帶後綴
     * @param waitZipFileRealPaths  需要壓縮的文件路徑集合
     * @return 生成的壓縮文件路徑
     * @throws Exception 異常
     */
    public static String createZipFile(String fileName, List<String> waitZipFileRealPaths) throws Exception {
        String filePath = LocalFilePathUtil.createFilePath(fileName, ".zip");
        List<File> srcFiles = new ArrayList<>();
        for (String filePathName:waitZipFileRealPaths){
            File file = new File(filePathName);
            if(file.exists()){
                srcFiles.add(file);
            }
        }
        zipFiles((File[]) srcFiles.toArray(),null,new File(filePath));
        return filePath;
    }

    /**
     * 將一系列文件壓縮進zip文件
     * @param fileName zip文件的名稱,當deFilePath文件路徑爲空不帶後綴,deFilePath文件路徑不爲空必須帶後綴
     * @param waitZipFilesOutput  需要壓縮的文件的封裝輸出流實體類
     * @param deFilePath  指定文件壓縮後的文件路徑,可不指定,不指定調用系統application默認上傳路徑,這裏是便於測試
     * @return 生成的壓縮文件路徑
     * @throws Exception 異常
     */
    public static String createZipFile2(String fileName, List<FileOutDto> waitZipFilesOutput,String deFilePath) throws Exception {
        String filePath = null;
        if(!StringUtils.isEmpty(deFilePath)){
            File file = new File(deFilePath);
            if(!file.exists()){
                file.mkdirs();
            }
            filePath = deFilePath + fileName;
        }else {
            filePath = LocalFilePathUtil.createFilePath(fileName, ".zip");
        }
        zipFiles(null,waitZipFilesOutput,new File(filePath));
        return filePath;
    }

    public static void zipFiles(File[] srcFiles, List<FileOutDto> fileOutDtos,File zipFile) throws Exception {
        // 判斷壓縮後的文件存在不,不存在則創建
        if (!zipFile.exists()) {
            zipFile.createNewFile();
        }
        // 創建 FileOutputStream 對象
        FileOutputStream fileOutputStream = null;
        // 創建 ZipOutputStream
        ZipOutputStream zipOutputStream = null;
        // 創建 FileInputStream 對象
        FileInputStream fileInputStream = null;

        // 實例化 FileOutputStream 對象
        fileOutputStream = new FileOutputStream(zipFile);
        // 實例化 ZipOutputStream 對象
        zipOutputStream = new ZipOutputStream(fileOutputStream);
        // 創建 ZipEntry 對象
        ZipEntry zipEntry = null;
        // 遍歷源文件數組
        if(null != srcFiles){
            for (int i = 0; i < srcFiles.length; i++) {
                // 將源文件數組中的當前文件讀入 FileInputStream 流中
                fileInputStream = new FileInputStream(srcFiles[i]);
                // 實例化 ZipEntry 對象,源文件數組中的當前文件
                zipEntry = new ZipEntry(srcFiles[i].getName());
                zipOutputStream.putNextEntry(zipEntry);
                // 該變量記錄每次真正讀的字節個數
                int len;
                // 定義每次讀取的字節數組
                byte[] buffer = new byte[1024];
                while ((len = fileInputStream.read(buffer)) > 0) {
                    zipOutputStream.write(buffer, 0, len);
                }
            }
        }else {
            if(!CollectionUtils.isEmpty(fileOutDtos)){
              for(FileOutDto fileOutDto : fileOutDtos) {
                  // 實例化 ZipEntry 對象,源文件數組中的當前文件
                  zipEntry = new ZipEntry(fileOutDto.getFileName());
                  zipOutputStream.putNextEntry(zipEntry);

                  ByteArrayOutputStream byteArrayOutputStream = fileOutDto.getByteArrayOutputStream();
                  byte[] bytes = byteArrayOutputStream.toByteArray();
                  zipOutputStream.write(bytes,0,bytes.length);
              }
            }
        }
        zipOutputStream.closeEntry();
        zipOutputStream.close();
        if(null != fileInputStream){
            fileInputStream.close();
        }
        fileOutputStream.close();
    }

    /**
     * s
     * 壓縮單個文件或者文件夾及其子文件夾進zip
     *
     * @param srcFilePath  壓縮源路徑
     * @param destFilePath 壓縮目的路徑
     */
    public static void compress(String srcFilePath, String destFilePath) {
        File src = new File(srcFilePath);
        if (!src.exists()) {
            throw new RuntimeException(srcFilePath + "不存在");
        }
        File zipFile = new File(destFilePath);
        try {
            FileOutputStream fos = new FileOutputStream(zipFile);
            ZipOutputStream zos = new ZipOutputStream(fos);
            String baseDir = "";
            compressbyType(src, zos, baseDir);
            zos.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 按照原路徑的類型就行壓縮。文件路徑直接把文件壓縮,
     *
     * @param src
     * @param zos
     * @param baseDir
     */
    private static void compressbyType(File src, ZipOutputStream zos, String baseDir) {
        if (!src.exists())
            return;
        System.out.println("壓縮路徑" + baseDir + src.getName());
        //判斷文件是否是文件,如果是文件調用compressFile方法,如果是路徑,則調用compressDir方法;
        if (src.isFile()) {
            //src是文件,調用此方法
            compressFile(src, zos, baseDir);
        } else if (src.isDirectory()) {
            //src是文件夾,調用此方法
            compressDir(src, zos, baseDir);
        }
    }

    /**
     * 壓縮文件
     */
    private static void compressFile(File file, ZipOutputStream zos, String baseDir) {
        if (!file.exists())
            return;
        try {
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
            ZipEntry entry = new ZipEntry(baseDir + file.getName());
            zos.putNextEntry(entry);
            int count;
            byte[] buf = new byte[1024];
            while ((count = bis.read(buf)) != -1) {
                zos.write(buf, 0, count);
            }
            bis.close();

        } catch (Exception e) {
            // TODO: handle exception

        }
    }

    /**
     * 壓縮文件夾
     */
    private static void compressDir(File dir, ZipOutputStream zos, String baseDir) {
        if (!dir.exists())
            return;
        File[] files = dir.listFiles();
        if (files.length == 0) {
            try {
                zos.putNextEntry(new ZipEntry(baseDir + dir.getName() + File.separator));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        for (File file : files) {
            compressbyType(file, zos, baseDir + dir.getName() + File.separator);
        }
    }

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @Accessors(chain = true)
    public static class FileOutDto{
        private String fileName;
        private ByteArrayOutputStream byteArrayOutputStream;
    }

    public static void main(String[] args) throws Exception {
        compress("D:/file/測試.png", "D:/file/測試.zip");
        compress("D:/file/測試.pdf", "D:/file/測試.zip");

//        File[] srcFiles = { new File("D:/file/測試.png"), new File("D:/file/測試.pdf")};
//        File zipFile = new File("D:/file/測試2.zip");
//        // 調用壓縮方法
//        zipFiles(srcFiles, zipFile);
        String[] srcFilePath = {"D:/file/測試.png","D:/file/測試.pdf"};

        String path = createZipFile("測試2", Arrays.asList(srcFilePath));
    }


}

二維碼生成工具類:

import com.google.zxing.*;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.xx.common.core.domain.AjaxResult;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Random;

/**
 *  
 *  * @projectName xx
 *  * @title     QRCodeUtil   
 *  * @package    com.xx.common.utils  
 *  * @description    二維碼生成工具
 *  * @author IT_CREAT     
 *  * @date  2019 2019/11/5 14:25  
 *  * @version V1.0.0 
 *  
 */
@Slf4j
@Data
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
public class QRCodeUtil {

    /**編碼utf-8*/
    private static final String CHARSET = "utf-8";
    /**二維碼圖片格式JPG*/
    private static final String FORMAT_NAME = "JPG";

    /**二維碼尺寸*/
    private int QRCODE_SIZE = 300;
    /**LOGO寬度*/
    private int WIDTH = 100;
    /**LOGO高度*/
    private int HEIGHT = 100;

    private Image srcImg = null;


    public static QRCodeUtil create(){
        return new QRCodeUtil();
    }

    /**
     * 生成二維碼
     * @param content	源內容
     * @param imgPath	生成二維碼保存的路徑
     * @param needCompress	是否要壓縮logo圖片,當logo大於設置高寬進行壓縮
     * @param useSetWidthAndHeight	在設置logo爲壓縮的情況下,是否直接啓用設置的高寬
     * @return		返回二維碼圖片
     * @throws Exception
     */
    private BufferedImage createImage(String content, String imgPath, InputStream logoImgInput,boolean needCompress,boolean useSetWidthAndHeight) throws Exception {
        Hashtable hints = new Hashtable();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
        hints.put(EncodeHintType.MARGIN, 1);
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE,
                hints);
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }
        if ((imgPath == null || "".equals(imgPath)) && ObjectUtils.isEmpty(logoImgInput)) {
            return image;
        }
        // 插入圖片
        insertImage(image, imgPath,logoImgInput,needCompress,useSetWidthAndHeight);
        return image;
    }

    /**
     * 在生成的二維碼中插入圖片
     * @param source
     * @param imgPath
     * @param needCompress
     * @throws Exception
     */
    private void insertImage(BufferedImage source, String imgPath,InputStream logoImgInput, boolean needCompress,boolean useSetWidthAndHeight) throws Exception {
        Image src = null;
        if(ObjectUtils.isEmpty(logoImgInput)){
            File file1 = new File(imgPath);
            if (!file1.exists()) {
                System.err.println("" + imgPath + "   該文件不存在!");
                return;
            }
            src = ImageIO.read(new File(imgPath));
        }else {
            src = ImageIO.read(logoImgInput);
        }
        if(ObjectUtils.isEmpty(srcImg)){
            srcImg = src;
        }else {
            src = srcImg;
        }
        int width = src.getWidth(null);
        int height = src.getHeight(null);
        if (needCompress) { // 壓縮LOGO
            if(useSetWidthAndHeight){
                width = this.WIDTH;
                height = this.HEIGHT;
            }else {
                if (width > this.WIDTH) {
                    width = this.WIDTH;
                }
                if (height > this.HEIGHT) {
                    height = this.HEIGHT;
                }
            }
            Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH);
            BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics g = tag.getGraphics();
            g.drawImage(image, 0, 0, null); // 繪製縮小後的圖
            g.dispose();
            src = image;
        }
        // 插入LOGO
        Graphics2D graph = source.createGraphics();
        int x = (QRCODE_SIZE - width) / 2;
        int y = (QRCODE_SIZE - height) / 2;
        graph.drawImage(src, x, y, width, height, null);
        Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
        graph.setStroke(new BasicStroke(3f));
        graph.draw(shape);
        graph.dispose();
    }

    /**
     * 生成帶logo二維碼,並保存到磁盤
     * @param content 二維碼內容
     * @param imgPath	logo圖片
     * @param destPath  二維碼輸出路徑
     * @param needCompress 是否需要壓縮logo圖片
     * @param fileName 二維碼文件名稱帶後綴
     * @throws Exception 異常
     */
    public void encode(String content, String imgPath,InputStream logoImgInput, String destPath, boolean needCompress,String fileName) throws Exception {
        BufferedImage image = createImage(content, imgPath,logoImgInput, needCompress,false);
        mkdirs(destPath);

        ImageIO.write(image, FORMAT_NAME, new File(destPath + "/" + fileName));
    }

    /**
     * 生成帶logo二維碼,返回輸出流
     * @param content 二維碼內容
     * @param imgPath logo圖片路徑
     * @param needCompress 是否需要壓縮
     * @return 二維碼輸出流
     * @throws Exception
     */
    public ByteArrayOutputStream encode2(String content, String imgPath, InputStream logoImgInput,boolean needCompress,boolean useSetWidthAndHeight) throws Exception {
        BufferedImage image = createImage(content, imgPath,logoImgInput, needCompress,useSetWidthAndHeight);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        boolean write = ImageIO.write(image, FORMAT_NAME, outputStream);
        if(write == true){
            return outputStream;
        }
        return null;
    }

    /**
     * 生成二維碼並打包壓縮
     * @param doubleCode  需要生成的二維碼內容集合
     * @param logoImgPath logo圖片地址
     * @param logoImgInput logo圖片輸入流,可傳入地址或輸入流二選一,優先輸入流
     * @param needCompress 是否需要圖片壓縮
     * @param useSetWidthAndHeight 在設置logo爲壓縮的情況下,是否直接啓用設置的高寬
     * @param zipName zip壓縮包的名字
     * @param zipPath 指定文件壓縮後的文件路徑,可不指定,不指定調用系統application默認上傳路徑,這裏是便於測試
     * @return 狀態信息
     */
    public AjaxResult createCode2Zip(List<DoubleCode> doubleCode, String logoImgPath, InputStream logoImgInput, boolean needCompress,boolean useSetWidthAndHeight, String zipName, String zipPath){
        if(CollectionUtils.isEmpty(doubleCode)){
            return AjaxResult.error("需要生成的二維碼內容爲空,無法生成");
        }
        try {
            List<ZipUtil.FileOutDto> fileOutDtos = new ArrayList<>();
            for(DoubleCode code:doubleCode){
                ByteArrayOutputStream outputStream = encode2(code.getCreateImgContent(), logoImgPath, logoImgInput,needCompress,useSetWidthAndHeight);
                if(null != outputStream){
                    ZipUtil.FileOutDto fileOutDto = new ZipUtil.FileOutDto();
                    fileOutDto.setFileName(code.getCreateImgName())
                            .setByteArrayOutputStream(outputStream);
                    fileOutDtos.add(fileOutDto);
                }
            }
            String zipFile2 = ZipUtil.createZipFile2(zipName, fileOutDtos,zipPath);
            return AjaxResult.success(zipFile2);
        }catch (Exception e){
            e.printStackTrace();
            log.info(e.getMessage());
            return AjaxResult.error("生成二維碼出現異常,請聯繫管理員或稍後重試");
        }
    }

    public void mkdirs(String destPath) {
        File file = new File(destPath);
        // 當文件夾不存在時,mkdirs會自動創建多層目錄,區別於mkdir。(mkdir如果父目錄不存在則會拋出異常)
        if (!file.exists() && !file.isDirectory()) {
            file.mkdirs();
        }
    }

    public void encode(String content, String imgPath, String destPath,String file) throws Exception {
        encode(content, imgPath, null,destPath, false ,file);
    }

    public void encode(String content, String destPath, boolean needCompress,String file) throws Exception {
        encode(content, null, null,destPath, needCompress,file);
    }

    public void encode(String content, String destPath,String file) throws Exception {
        encode(content, null, null,destPath, false,file);
    }

    public void encode(String content, String imgPath, OutputStream output, boolean needCompress)
            throws Exception {
        BufferedImage image = createImage(content, imgPath,null, needCompress,false);
        ImageIO.write(image, FORMAT_NAME, output);
    }

    public void encode(String content, OutputStream output) throws Exception {
        encode(content, null, output, false);
    }

    /**
     * 從二維碼中,解析數據
     * @param file	二維碼圖片文件
     * @return	 返回從二維碼中解析到的數據值
     * @throws Exception
     */
    public String decode(File file) throws Exception {
        BufferedImage image;
        image = ImageIO.read(file);
        if (image == null) {
            return null;
        }
        BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
        Result result;
        Hashtable hints = new Hashtable();
        hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
        result = new MultiFormatReader().decode(bitmap, hints);
        String resultStr = result.getText();
        return resultStr;
    }

    public String decode(String path) throws Exception {
        return decode(new File(path));
    }

    /**二維碼需要生成內容的實體類*/
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @Accessors(chain = true)
    public static class DoubleCode{
        /**生成二維碼圖片的名字帶後綴,必須爲jpg*/
        private String createImgName;
        /**生成二維碼的內容*/
        private String createImgContent;
    }


    /**測試*/
    public static void main(String[] args) throws Exception {
        String textt = "xxxxxx二維碼";//二維碼的內容
        String logo = "d:"+"/logo.png";//logo的路徑
        String file = new Random().nextInt(99999999) + ".jpg";//生成隨機文件名
        System.out.println("生成二維碼文件名"+file.toString());
        String path = "D:/";

        QRCodeUtil.create().encode(textt,logo,null,path,true,file);//path 二維碼保存的服務器的路徑


        List<DoubleCode> doubleCodes = new ArrayList<>();
        DoubleCode code = new DoubleCode();
        code.setCreateImgName("蘋果筆記本-0006878954725.jpg")
                .setCreateImgContent("0006878954725");
        doubleCodes.add(code);
        code = new DoubleCode();
        code.setCreateImgName("華爲筆記本-0006866754725.jpg")
                .setCreateImgContent("0006866754725");
        doubleCodes.add(code);
        AjaxResult result = QRCodeUtil.create().createCode2Zip(doubleCodes, logo,null, true, false,"二維碼壓縮包.zip", "D:/");
        System.out.println(result);
    }




}

 

獲取本地文件路徑工具類:

import com.xx.common.config.Global;

import java.io.File;
import java.util.UUID;

/**
 *  
 *  * @projectName ruoyi
 *  * @title     LocalFilePathUtil   
 *  * @package    com.ruoyi.common.utils  
 *  * @description    快速創建文件全路徑工具類
 *  * @author IT_CREAT     
 *  * @date  2019 2019/9/30 2:03  
 *  * @version V1.0.0 
 *  
 */
public class LocalFilePathUtil {

    /**
     * 快速創建本地文件全路徑路徑名
     * @param filename 文件名字 如:" 測試文件 "
     * @param suffix 文件後綴 :如:" .pdf "
     * @return 全路徑名
     */
    public static String createFilePath(String filename, String suffix){
        String fileName = encodingFilename(filename, suffix);
        return getAbsoluteFile(fileName);
    }

    /**
     * 編碼文件名
     *
     * @param filename 文件名稱
     * @param suffix   文件後綴
     * @return 編碼後的文件名
     */
    public static String encodingFilename(String filename, String suffix) {
        filename = UUID.randomUUID().toString() + "_" + filename + suffix;
        return filename;
    }

    /**
     * 獲取下載路徑
     *
     * @param filename 文件名稱
     */
    public static String getAbsoluteFile(String filename) {
        String downloadPath = Global.getDownloadPath() + filename;
        File desc = new File(downloadPath);
        if (!desc.getParentFile().exists()) {
            desc.getParentFile().mkdirs();
        }
        return downloadPath;
    }



}

 

 

 

 

全局配置類:

application.yml

# 項目相關配置
vcsrm:
  # 名稱
  name: vcsrm_dxl
  # 版本
  version: 4.0.0
  # 版權年份
  copyrightYear: 2019
  # 實例演示開關
  demoEnabled: true
  # 文件路徑 示例( Windows配置D:/vcsrm/uploadPath,Linux配置 /home/vcsrm/uploadPath)
  profile: /home/vcsrm/uploadPath
  # 獲取ip地址開關
  addressEnabled: true

java類:

 
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.xx.common.utils.StringUtils;
import com.xx.common.utils.YamlUtil;

/**
 * 全局配置類
 * 
 * @author xx
 */
public class Global
{
    private static final Logger log = LoggerFactory.getLogger(Global.class);

    private static String NAME = "application.yml";

    /**
     * 當前對象實例
     */
    private static Global global;

    /**
     * 保存全局屬性值
     */
    private static Map<String, String> map = new HashMap<String, String>();

    private Global()
    {
    }

    /**
     * 靜態工廠方法
     */
    public static synchronized Global getInstance()
    {
        if (global == null)
        {
            global = new Global();
        }
        return global;
    }

    /**
     * 獲取配置
     */
    public static String getConfig(String key)
    {
        String value = map.get(key);
        if (value == null)
        {
            Map<?, ?> yamlMap = null;
            try
            {
                yamlMap = YamlUtil.loadYaml(NAME);
                value = String.valueOf(YamlUtil.getProperty(yamlMap, key));
                map.put(key, value != null ? value : StringUtils.EMPTY);
            }
            catch (FileNotFoundException e)
            {
                log.error("獲取全局配置異常 {}", key);
            }
        }
        return value;
    }

    /**
     * 獲取項目名稱
     */
    public static String getName()
    {
        return StringUtils.nvl(getConfig("vcsrm.name"), "RuoYi");
    }

    /**
     * 獲取項目版本
     */
    public static String getVersion()
    {
        return StringUtils.nvl(getConfig("vcsrm.version"), "4.0.0");
    }

    /**
     * 獲取版權年份
     */
    public static String getCopyrightYear()
    {
        return StringUtils.nvl(getConfig("vcsrm.copyrightYear"), "2019");
    }

    /**
     * 實例演示開關
     */
    public static String isDemoEnabled()
    {
        return StringUtils.nvl(getConfig("vcsrm.demoEnabled"), "true");
    }

    /**
     * 獲取ip地址開關
     */
    public static Boolean isAddressEnabled()
    {
        return Boolean.valueOf(getConfig("vcsrm.addressEnabled"));
    }

    /**
     * 獲取文件上傳路徑
     */
    public static String getProfile()
    {
        return getConfig("vcsrm.profile");
    }

    /**
     * 獲取頭像上傳路徑
     */
    public static String getAvatarPath()
    {
        return getProfile() + "/avatar";
    }

    /**
     * 獲取下載路徑
     */
    public static String getDownloadPath()
    {
        return getProfile() + "/download/";
    }

    /**
     * 獲取上傳路徑
     */
    public static String getUploadPath()
    {
        return getProfile() + "/upload";
    }
}

yaml文件操作工具類:

import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;

import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 配置處理工具類
 * 
 * @author yml
 */
public class YamlUtil
{
    public static Map<?, ?> loadYaml(String fileName) throws FileNotFoundException
    {
        InputStream in = YamlUtil.class.getClassLoader().getResourceAsStream(fileName);
        return StringUtils.isNotEmpty(fileName) ? (LinkedHashMap<?, ?>) new Yaml().load(in) : null;
    }

    public static void dumpYaml(String fileName, Map<?, ?> map) throws IOException
    {
        if (StringUtils.isNotEmpty(fileName))
        {
            FileWriter fileWriter = new FileWriter(YamlUtil.class.getResource(fileName).getFile());
            DumperOptions options = new DumperOptions();
            options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
            Yaml yaml = new Yaml(options);
            yaml.dump(map, fileWriter);
        }
    }

    public static Object getProperty(Map<?, ?> map, Object qualifiedKey)
    {
        if (map != null && !map.isEmpty() && qualifiedKey != null)
        {
            String input = String.valueOf(qualifiedKey);
            if (!"".equals(input))
            {
                if (input.contains("."))
                {
                    int index = input.indexOf(".");
                    String left = input.substring(0, index);
                    String right = input.substring(index + 1, input.length());
                    return getProperty((Map<?, ?>) map.get(left), right);
                }
                else if (map.containsKey(input))
                {
                    return map.get(input);
                }
                else
                {
                    return null;
                }
            }
        }
        return null;
    }

    @SuppressWarnings("unchecked")
    public static void setProperty(Map<?, ?> map, Object qualifiedKey, Object value)
    {
        if (map != null && !map.isEmpty() && qualifiedKey != null)
        {
            String input = String.valueOf(qualifiedKey);
            if (!input.equals(""))
            {
                if (input.contains("."))
                {
                    int index = input.indexOf(".");
                    String left = input.substring(0, index);
                    String right = input.substring(index + 1, input.length());
                    setProperty((Map<?, ?>) map.get(left), right, value);
                }
                else
                {
                    ((Map<Object, Object>) map).put(qualifiedKey, value);
                }
            }
        }
    }
}

需要引入:

<!-- yml解析器 -->
<dependency>
    <groupId>org.yaml</groupId>
    <artifactId>snakeyaml</artifactId>
</dependency>

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章