效果:
首先引入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>