代码优化

This commit is contained in:
thinkgem
2025-08-08 13:48:20 +08:00
parent abb63bf547
commit 1a6d1b2a2e
27 changed files with 341 additions and 424 deletions

View File

@@ -32,7 +32,7 @@ import java.util.regex.Pattern;
* 4. JDK 提供的 URLEncoder * 4. JDK 提供的 URLEncoder
* 5. XSS、SQL、orderBy 过滤器 * 5. XSS、SQL、orderBy 过滤器
* @author calvin、ThinkGem * @author calvin、ThinkGem
* @version 2022-2-17 * @version 2025-7-9
*/ */
public class EncodeUtils { public class EncodeUtils {

View File

@@ -24,20 +24,20 @@ public class CommandUtils {
public static String execute(String command, String charsetName) throws IOException { public static String execute(String command, String charsetName) throws IOException {
Process process = Runtime.getRuntime().exec(command); Process process = Runtime.getRuntime().exec(command);
// 记录dos命令的返回信息 // 记录dos命令的返回信息
StringBuffer stringBuffer = new StringBuffer(); StringBuilder sb = new StringBuilder();
// 获取返回信息的流 // 获取返回信息的流
InputStream in = process.getInputStream(); InputStream in = process.getInputStream();
Reader reader = new InputStreamReader(in, charsetName); Reader reader = new InputStreamReader(in, charsetName);
BufferedReader bReader = new BufferedReader(reader); BufferedReader bReader = new BufferedReader(reader);
String res = bReader.readLine(); String res = bReader.readLine();
while (res != null) { while (res != null) {
stringBuffer.append(res); sb.append(res);
stringBuffer.append("\n"); sb.append("\n");
res = bReader.readLine(); res = bReader.readLine();
} }
bReader.close(); bReader.close();
reader.close(); reader.close();
return stringBuffer.toString(); return sb.toString();
} }
} }

View File

@@ -4,26 +4,21 @@
*/ */
package com.jeesite.common.image; package com.jeesite.common.image;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import org.patchca.background.BackgroundFactory; import org.patchca.background.BackgroundFactory;
import org.patchca.color.ColorFactory; import org.patchca.color.ColorFactory;
import org.patchca.filter.predefined.CurvesRippleFilterFactory; import org.patchca.filter.predefined.*;
import org.patchca.filter.predefined.DiffuseRippleFilterFactory;
import org.patchca.filter.predefined.DoubleRippleFilterFactory;
import org.patchca.filter.predefined.MarbleRippleFilterFactory;
import org.patchca.filter.predefined.WobbleRippleFilterFactory;
import org.patchca.font.RandomFontFactory; import org.patchca.font.RandomFontFactory;
import org.patchca.service.ConfigurableCaptchaService; import org.patchca.service.ConfigurableCaptchaService;
import org.patchca.text.renderer.BestFitTextRenderer; import org.patchca.text.renderer.BestFitTextRenderer;
import org.patchca.utils.encoder.EncoderHelper; import org.patchca.utils.encoder.EncoderHelper;
import org.patchca.word.RandomWordFactory; import org.patchca.word.RandomWordFactory;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
/** /**
* 验证码工具 * 验证码工具
* @author ThinkGem * @author ThinkGem
@@ -31,7 +26,7 @@ import org.patchca.word.RandomWordFactory;
*/ */
public class CaptchaUtils { public class CaptchaUtils {
private static Random random = new Random(); private static final Random random = new Random();
private volatile static ConfigurableCaptchaService ccs; private volatile static ConfigurableCaptchaService ccs;
private static WobbleRippleFilterFactory wrff; // 摆波纹 private static WobbleRippleFilterFactory wrff; // 摆波纹
private static DoubleRippleFilterFactory doff; // 双波纹 private static DoubleRippleFilterFactory doff; // 双波纹
@@ -135,9 +130,6 @@ public class CaptchaUtils {
/** /**
* 生成验证码 * 生成验证码
* @param request
* @param response
* @throws IOException
* @return 验证码字符 * @return 验证码字符
*/ */
public static String generateCaptcha(OutputStream outputStream) throws IOException{ public static String generateCaptcha(OutputStream outputStream) throws IOException{

View File

@@ -11,7 +11,7 @@
//import com.drew.metadata.exif.GpsDirectory; //import com.drew.metadata.exif.GpsDirectory;
// //
///** ///**
// * 图片地理信息获取 // * 图片地理信息获取pom.xml 中打开 com.drewnoakes 依赖)
// * @author ThinkGem // * @author ThinkGem
// */ // */
//public class ImageGeo { //public class ImageGeo {

View File

@@ -68,7 +68,7 @@ public class ImageUtils {
bilder.toFile(targetFile); bilder.toFile(targetFile);
} }
}catch(IOException e){ }catch(IOException e){
logger.error("图片压缩失败:" + imageFile.getAbsoluteFile(), e); logger.error("图片压缩失败:{}", imageFile.getAbsoluteFile(), e);
} }
} }

View File

@@ -10,6 +10,8 @@ import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix; import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer; import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.imageio.ImageIO; import javax.imageio.ImageIO;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
@@ -23,13 +25,14 @@ import java.util.Hashtable;
*/ */
public class ZxingUtils { public class ZxingUtils {
private static final Logger logger = LoggerFactory.getLogger(ZxingUtils.class);
/** /**
* 条形码编码 * 条形码编码
* * @param contents 内容
* @param contents * @param width 宽度
* @param width * @param height 高度
* @param height * @param imgPath 图片路径
* @param imgPath
*/ */
public static void encode(String contents, int width, int height, String imgPath) { public static void encode(String contents, int width, int height, String imgPath) {
int codeWidth = 3 + // start guard int codeWidth = 3 + // start guard
@@ -42,14 +45,13 @@ public class ZxingUtils {
BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.EAN_13, codeWidth, height, null); BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.EAN_13, codeWidth, height, null);
MatrixToImageWriter.writeToPath(bitMatrix, "png", new File(imgPath).toPath()); MatrixToImageWriter.writeToPath(bitMatrix, "png", new File(imgPath).toPath());
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); logger.error(e.getMessage(), e);
} }
} }
/** /**
* 条形码解码 * 条形码解码
* * @param imgPath 图片路径
* @param imgPath
* @return String * @return String
*/ */
public static String decode(String imgPath) { public static String decode(String imgPath) {
@@ -58,25 +60,24 @@ public class ZxingUtils {
try { try {
image = ImageIO.read(new File(imgPath)); image = ImageIO.read(new File(imgPath));
if (image == null) { if (image == null) {
System.out.println("the decode image may be not exit."); logger.debug("the decode image may be not exit.");
} }
LuminanceSource source = new BufferedImageLuminanceSource(image); LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
result = new MultiFormatReader().decode(bitmap, null); result = new MultiFormatReader().decode(bitmap, null);
return result.getText(); return result.getText();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); logger.error(e.getMessage(), e);
} }
return null; return null;
} }
/** /**
* 二维码编码 * 二维码编码
* * @param contents 内容
* @param contents * @param width 宽度
* @param width * @param height 高度
* @param height * @param imgPath 图片路径
* @param imgPath
*/ */
public static void encode2(String contents, int width, int height, String imgPath) { public static void encode2(String contents, int width, int height, String imgPath) {
Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>(); Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
@@ -88,14 +89,13 @@ public class ZxingUtils {
BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, width, height, hints); BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, width, height, hints);
MatrixToImageWriter.writeToPath(bitMatrix, "png", new File(imgPath).toPath()); MatrixToImageWriter.writeToPath(bitMatrix, "png", new File(imgPath).toPath());
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); logger.error(e.getMessage(), e);
} }
} }
/** /**
* 二维码解码 * 二维码解码
* * @param imgPath 图片路径
* @param imgPath
* @return String * @return String
*/ */
public static String decode2(String imgPath) { public static String decode2(String imgPath) {
@@ -104,7 +104,7 @@ public class ZxingUtils {
try { try {
image = ImageIO.read(new File(imgPath)); image = ImageIO.read(new File(imgPath));
if (image == null) { if (image == null) {
System.out.println("the decode image may be not exit."); logger.debug("the decode image may be not exit.");
} }
LuminanceSource source = new BufferedImageLuminanceSource(image); LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
@@ -113,7 +113,7 @@ public class ZxingUtils {
result = new MultiFormatReader().decode(bitmap, hints); result = new MultiFormatReader().decode(bitmap, hints);
return result.getText(); return result.getText();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); logger.error(e.getMessage(), e);
} }
return null; return null;
} }

View File

@@ -19,6 +19,8 @@ import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.io.*; import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.Enumeration; import java.util.Enumeration;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
@@ -30,7 +32,7 @@ import java.util.zip.ZipOutputStream;
* 文件操作工具类 * 文件操作工具类
* 实现文件的创建、删除、复制、压缩、解压以及目录的创建、删除、复制、压缩解压等功能 * 实现文件的创建、删除、复制、压缩、解压以及目录的创建、删除、复制、压缩解压等功能
* @author ThinkGem * @author ThinkGem
* @version 2015-3-16 * @version 2025-08-08
*/ */
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public class FileUtils extends org.apache.commons.io.FileUtils { public class FileUtils extends org.apache.commons.io.FileUtils {
@@ -57,17 +59,16 @@ public class FileUtils extends org.apache.commons.io.FileUtils {
* @param coverlay 如果目标文件已存在,是否覆盖 * @param coverlay 如果目标文件已存在,是否覆盖
* @return 如果复制成功则返回true否则返回false * @return 如果复制成功则返回true否则返回false
*/ */
public static boolean copyFileCover(String srcFileName, public static boolean copyFileCover(String srcFileName, String descFileName, boolean coverlay) {
String descFileName, boolean coverlay) {
File srcFile = new File(srcFileName); File srcFile = new File(srcFileName);
// 判断源文件是否存在 // 判断源文件是否存在
if (!srcFile.exists()) { if (!srcFile.exists()) {
logger.debug("复制文件失败,源文件 " + srcFileName + " 不存在!"); logger.debug("复制文件失败,源文件 {} 不存在!", srcFileName);
return false; return false;
} }
// 判断源文件是否是合法的文件 // 判断源文件是否是合法的文件
else if (!srcFile.isFile()) { else if (!srcFile.isFile()) {
logger.debug("复制文件失败," + srcFileName + " 不是一个文件!"); logger.debug("复制文件失败,{} 不是一个文件!", srcFileName);
return false; return false;
} }
File descFile = new File(descFileName); File descFile = new File(descFileName);
@@ -77,11 +78,11 @@ public class FileUtils extends org.apache.commons.io.FileUtils {
if (coverlay) { if (coverlay) {
logger.debug("目标文件已存在,准备删除!"); logger.debug("目标文件已存在,准备删除!");
if (!FileUtils.delFile(descFileName)) { if (!FileUtils.delFile(descFileName)) {
logger.debug("删除目标文件 " + descFileName + " 失败!"); logger.debug("删除目标文件 {} 失败!", descFileName);
return false; return false;
} }
} else { } else {
logger.debug("复制文件失败,目标文件 " + descFileName + " 已存在!"); logger.debug("复制文件失败,目标文件 {} 已存在!", descFileName);
return false; return false;
} }
} else { } else {
@@ -95,45 +96,26 @@ public class FileUtils extends org.apache.commons.io.FileUtils {
} }
} }
} }
// 准备复制文件 // 准备复制文件
try (
// 打开源文件
InputStream ins = Files.newInputStream(srcFile.toPath());
// 打开目标文件的输出流
OutputStream outs = Files.newOutputStream(descFile.toPath());
) {
// 读取的位数 // 读取的位数
int readByte = 0; int readByte = 0;
InputStream ins = null;
OutputStream outs = null;
try {
// 打开源文件
ins = new FileInputStream(srcFile);
// 打开目标文件的输出流
outs = new FileOutputStream(descFile);
byte[] buf = new byte[1024];
// 一次读取1024个字节当readByte为-1时表示文件已经读取完毕 // 一次读取1024个字节当readByte为-1时表示文件已经读取完毕
byte[] buf = new byte[1024];
while ((readByte = ins.read(buf)) != -1) { while ((readByte = ins.read(buf)) != -1) {
// 将读取的字节流写入到输出流 // 将读取的字节流写入到输出流
outs.write(buf, 0, readByte); outs.write(buf, 0, readByte);
} }
logger.debug("复制单个文件 " + srcFileName + "" + descFileName logger.debug("复制单个文件 {} 到{}成功!", srcFileName, descFileName);
+ "成功!");
return true; return true;
} catch (Exception e) { } catch (Exception e) {
logger.debug("复制文件失败:" + e.getMessage()); logger.debug("复制文件失败:{}", e.getMessage());
return false; return false;
} finally {
// 关闭输入输出流,首先关闭输出流,然后再关闭输入流
if (outs != null) {
try {
outs.close();
} catch (IOException oute) {
oute.printStackTrace();
}
}
if (ins != null) {
try {
ins.close();
} catch (IOException ine) {
ine.printStackTrace();
}
}
} }
} }
@@ -144,8 +126,7 @@ public class FileUtils extends org.apache.commons.io.FileUtils {
* @return 如果复制成功返回true否则返回false * @return 如果复制成功返回true否则返回false
*/ */
public static boolean copyDirectory(String srcDirName, String descDirName) { public static boolean copyDirectory(String srcDirName, String descDirName) {
return FileUtils.copyDirectoryCover(srcDirName, descDirName, return FileUtils.copyDirectoryCover(srcDirName, descDirName, false);
false);
} }
/** /**
@@ -155,17 +136,16 @@ public class FileUtils extends org.apache.commons.io.FileUtils {
* @param coverlay 如果目标目录存在,是否覆盖 * @param coverlay 如果目标目录存在,是否覆盖
* @return 如果复制成功返回true否则返回false * @return 如果复制成功返回true否则返回false
*/ */
public static boolean copyDirectoryCover(String srcDirName, public static boolean copyDirectoryCover(String srcDirName, String descDirName, boolean coverlay) {
String descDirName, boolean coverlay) {
File srcDir = new File(srcDirName); File srcDir = new File(srcDirName);
// 判断源目录是否存在 // 判断源目录是否存在
if (!srcDir.exists()) { if (!srcDir.exists()) {
logger.debug("复制目录失败,源目录 " + srcDirName + " 不存在!"); logger.debug("复制目录失败,源目录 {} 不存在!", srcDirName);
return false; return false;
} }
// 判断源目录是否是目录 // 判断源目录是否是目录
else if (!srcDir.isDirectory()) { else if (!srcDir.isDirectory()) {
logger.debug("复制目录失败," + srcDirName + " 不是一个目录!"); logger.debug("复制目录失败,{} 不是一个目录!", srcDirName);
return false; return false;
} }
// 如果目标文件夹名不以文件分隔符结尾,自动添加文件分隔符 // 如果目标文件夹名不以文件分隔符结尾,自动添加文件分隔符
@@ -180,11 +160,11 @@ public class FileUtils extends org.apache.commons.io.FileUtils {
// 允许覆盖目标目录 // 允许覆盖目标目录
logger.debug("目标目录已存在,准备删除!"); logger.debug("目标目录已存在,准备删除!");
if (!FileUtils.delFile(descDirNames)) { if (!FileUtils.delFile(descDirNames)) {
logger.debug("删除目录 " + descDirNames + " 失败!"); logger.debug("删除目录 {} 失败!", descDirNames);
return false; return false;
} }
} else { } else {
logger.debug("目标目录复制失败,目标目录 " + descDirNames + " 已存在!"); logger.debug("目标目录复制失败,目标目录 {} 已存在!", descDirNames);
return false; return false;
} }
} else { } else {
@@ -200,32 +180,31 @@ public class FileUtils extends org.apache.commons.io.FileUtils {
boolean flag = true; boolean flag = true;
// 列出源目录下的所有文件名和子目录名 // 列出源目录下的所有文件名和子目录名
File[] files = srcDir.listFiles(); File[] files = srcDir.listFiles();
for (int i = 0; i < files.length; i++) { if (files != null) {
for (File file : files) {
// 如果是一个单个文件,则直接复制 // 如果是一个单个文件,则直接复制
if (files[i].isFile()) { if (file.isFile()) {
flag = FileUtils.copyFile(files[i].getAbsolutePath(), flag = FileUtils.copyFile(file.getAbsolutePath(), descDirName + file.getName());
descDirName + files[i].getName());
// 如果拷贝文件失败,则退出循环 // 如果拷贝文件失败,则退出循环
if (!flag) { if (!flag) {
break; break;
} }
} }
// 如果是子目录,则继续复制目录 // 如果是子目录,则继续复制目录
if (files[i].isDirectory()) { if (file.isDirectory()) {
flag = FileUtils.copyDirectory(files[i] flag = FileUtils.copyDirectory(file.getAbsolutePath(), descDirName + file.getName());
.getAbsolutePath(), descDirName + files[i].getName());
// 如果拷贝目录失败,则退出循环 // 如果拷贝目录失败,则退出循环
if (!flag) { if (!flag) {
break; break;
} }
} }
} }
}
if (!flag) { if (!flag) {
logger.debug("复制目录 " + srcDirName + "" + descDirName + " 失败!"); logger.debug("复制目录 {} 到 {} 失败!", srcDirName, descDirName);
return false; return false;
} }
logger.debug("复制目录 " + srcDirName + "" + descDirName + " 成功!"); logger.debug("复制目录 {} 到 {} 成功!", srcDirName, descDirName);
return true; return true;
} }
@@ -238,7 +217,7 @@ public class FileUtils extends org.apache.commons.io.FileUtils {
*/ */
public static String readFileToString(String classResourcePath){ public static String readFileToString(String classResourcePath){
try (InputStream in = new ClassPathResource(classResourcePath).getInputStream()){ try (InputStream in = new ClassPathResource(classResourcePath).getInputStream()){
return IOUtils.toString(in, EncodeUtils.UTF_8); return IOUtils.toString(in, StandardCharsets.UTF_8);
} catch (IOException e) { } catch (IOException e) {
logger.warn("Error file convert: {}", e.getMessage()); logger.warn("Error file convert: {}", e.getMessage());
} }
@@ -246,16 +225,14 @@ public class FileUtils extends org.apache.commons.io.FileUtils {
} }
/** /**
*
* 删除文件,可以删除单个文件或文件夹 * 删除文件,可以删除单个文件或文件夹
*
* @param fileName 被删除的文件名 * @param fileName 被删除的文件名
* @return 如果删除成功则返回true否是返回false * @return 如果删除成功则返回true否是返回false
*/ */
public static boolean delFile(String fileName) { public static boolean delFile(String fileName) {
File file = new File(fileName); File file = new File(fileName);
if (!file.exists()) { if (!file.exists()) {
logger.debug(fileName + " 文件不存在!"); logger.debug("{} 文件不存在!", fileName);
return true; return true;
} else { } else {
if (file.isFile()) { if (file.isFile()) {
@@ -267,9 +244,7 @@ public class FileUtils extends org.apache.commons.io.FileUtils {
} }
/** /**
*
* 删除单个文件 * 删除单个文件
*
* @param fileName 被删除的文件名 * @param fileName 被删除的文件名
* @return 如果删除成功则返回true否则返回false * @return 如果删除成功则返回true否则返回false
*/ */
@@ -277,22 +252,20 @@ public class FileUtils extends org.apache.commons.io.FileUtils {
File file = new File(fileName); File file = new File(fileName);
if (file.exists() && file.isFile()) { if (file.exists() && file.isFile()) {
if (file.delete()) { if (file.delete()) {
logger.debug("删除文件 " + fileName + " 成功!"); logger.debug("删除文件 {} 成功!", fileName);
return true; return true;
} else { } else {
logger.debug("删除文件 " + fileName + " 失败!"); logger.debug("删除文件 {} 失败!", fileName);
return false; return false;
} }
} else { } else {
logger.debug(fileName + " 文件不存在!"); logger.debug("{} 文件不存在!", fileName);
return true; return true;
} }
} }
/** /**
*
* 删除目录及目录下的文件 * 删除目录及目录下的文件
*
* @param dirName 被删除的目录所在的文件路径 * @param dirName 被删除的目录所在的文件路径
* @return 如果目录删除成功则返回true否则返回false * @return 如果目录删除成功则返回true否则返回false
*/ */
@@ -309,36 +282,36 @@ public class FileUtils extends org.apache.commons.io.FileUtils {
boolean flag = true; boolean flag = true;
// 列出全部文件及子目录 // 列出全部文件及子目录
File[] files = dirFile.listFiles(); File[] files = dirFile.listFiles();
for (int i = 0; i < files.length; i++) { if (files != null) {
for (File file : files) {
// 删除子文件 // 删除子文件
if (files[i].isFile()) { if (file.isFile()) {
flag = FileUtils.deleteFile(files[i].getAbsolutePath()); flag = FileUtils.deleteFile(file.getAbsolutePath());
// 如果删除文件失败,则退出循环 // 如果删除文件失败,则退出循环
if (!flag) { if (!flag) {
break; break;
} }
} }
// 删除子目录 // 删除子目录
else if (files[i].isDirectory()) { else if (file.isDirectory()) {
flag = FileUtils.deleteDirectory(files[i] flag = FileUtils.deleteDirectory(file.getAbsolutePath());
.getAbsolutePath());
// 如果删除子目录失败,则退出循环 // 如果删除子目录失败,则退出循环
if (!flag) { if (!flag) {
break; break;
} }
} }
} }
}
if (!flag) { if (!flag) {
logger.debug("删除目录失败!"); logger.debug("删除目录失败!");
return false; return false;
} }
// 删除当前目录 // 删除当前目录
if (dirFile.delete()) { if (dirFile.delete()) {
logger.debug("删除目录 " + dirName + " 成功!"); logger.debug("删除目录 {} 成功!", dirName);
return true; return true;
} else { } else {
logger.debug("删除目录 " + dirName + " 失败!"); logger.debug("删除目录 {} 失败!", dirName);
return false; return false;
} }
@@ -352,11 +325,11 @@ public class FileUtils extends org.apache.commons.io.FileUtils {
public static boolean createFile(String descFileName) { public static boolean createFile(String descFileName) {
File file = new File(descFileName); File file = new File(descFileName);
if (file.exists()) { if (file.exists()) {
logger.debug("文件 " + descFileName + " 已存在!"); logger.debug("文件 {} 已存在!", descFileName);
return false; return false;
} }
if (descFileName.endsWith(File.separator)) { if (descFileName.endsWith(File.separator)) {
logger.debug(descFileName + " 为目录,不能创建目录!"); logger.debug("{} 为目录,不能创建目录!", descFileName);
return false; return false;
} }
if (!file.getParentFile().exists()) { if (!file.getParentFile().exists()) {
@@ -366,22 +339,19 @@ public class FileUtils extends org.apache.commons.io.FileUtils {
return false; return false;
} }
} }
// 创建文件 // 创建文件
try { try {
if (file.createNewFile()) { if (file.createNewFile()) {
logger.debug(descFileName + " 文件创建成功!"); logger.debug("{} 文件创建成功!", descFileName);
return true; return true;
} else { } else {
logger.debug(descFileName + " 文件创建失败!"); logger.debug("{} 文件创建失败!", descFileName);
return false; return false;
} }
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); logger.debug("{} 文件创建失败!", descFileName, e);
logger.debug(descFileName + " 文件创建失败!");
return false; return false;
} }
} }
/** /**
@@ -396,15 +366,15 @@ public class FileUtils extends org.apache.commons.io.FileUtils {
} }
File descDir = new File(descDirNames); File descDir = new File(descDirNames);
if (descDir.exists()) { if (descDir.exists()) {
logger.debug("目录 " + descDirNames + " 已存在!"); logger.debug("目录 {} 已存在!", descDirNames);
return false; return false;
} }
// 创建目录 // 创建目录
if (descDir.mkdirs()) { if (descDir.mkdirs()) {
logger.debug("目录 " + descDirNames + " 创建成功!"); logger.debug("目录 {} 创建成功!", descDirNames);
return true; return true;
} else { } else {
logger.debug("目录 " + descDirNames + " 创建失败!"); logger.debug("目录 {} 创建失败!", descDirNames);
return false; return false;
} }
@@ -417,9 +387,9 @@ public class FileUtils extends org.apache.commons.io.FileUtils {
public static void writeToFile(String fileName, String content, boolean append) { public static void writeToFile(String fileName, String content, boolean append) {
try { try {
FileUtils.write(new File(fileName), content, EncodeUtils.UTF_8, append); FileUtils.write(new File(fileName), content, EncodeUtils.UTF_8, append);
logger.debug("文件 " + fileName + " 写入成功!"); logger.debug("文件 {} 写入成功!", fileName);
} catch (IOException e) { } catch (IOException e) {
logger.debug("文件 " + fileName + " 写入失败! " + e.getMessage()); logger.debug("文件 {} 写入失败!", fileName, e);
} }
} }
@@ -430,9 +400,9 @@ public class FileUtils extends org.apache.commons.io.FileUtils {
public static void writeToFile(String fileName, String content, String encoding, boolean append) { public static void writeToFile(String fileName, String content, String encoding, boolean append) {
try { try {
FileUtils.write(new File(fileName), content, encoding, append); FileUtils.write(new File(fileName), content, encoding, append);
logger.debug("文件 " + fileName + " 写入成功!"); logger.debug("文件 {} 写入成功!", fileName);
} catch (IOException e) { } catch (IOException e) {
logger.debug("文件 " + fileName + " 写入失败! " + e.getMessage()); logger.debug("文件 {} 写入失败!", fileName, e);
} }
} }
@@ -447,12 +417,11 @@ public class FileUtils extends org.apache.commons.io.FileUtils {
return; return;
} }
byte[] data = EncodeUtils.decodeBase64(base64); byte[] data = EncodeUtils.decodeBase64(base64);
File file = new File(fileName); File file = new File(fileName);
try { try {
FileUtils.writeByteArrayToFile(file, data); FileUtils.writeByteArrayToFile(file, data);
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); logger.error("文件 {} 写入失败!", fileName, e);
} }
} }
@@ -470,33 +439,30 @@ public class FileUtils extends org.apache.commons.io.FileUtils {
public static void zipFiles(String srcDirName, String fileName, String descFileName) { public static void zipFiles(String srcDirName, String fileName, String descFileName) {
// 判断目录是否存在 // 判断目录是否存在
if (srcDirName == null) { if (srcDirName == null) {
logger.debug("文件压缩失败,目录 " + srcDirName + " 不存在!"); logger.debug("文件压缩失败,目录 {} 不存在!", srcDirName);
return; return;
} }
File fileDir = new File(srcDirName); File fileDir = new File(srcDirName);
if (!fileDir.exists() || !fileDir.isDirectory()) { if (!fileDir.exists() || !fileDir.isDirectory()) {
logger.debug("文件压缩失败,目录 " + srcDirName + " 不存在!"); logger.debug("文件压缩失败,目录 {} 不存在!", srcDirName);
return; return;
} }
String dirPath = fileDir.getAbsolutePath(); String dirPath = fileDir.getAbsolutePath();
File descFile = new File(descFileName); File descFile = new File(descFileName);
try { try (ZipOutputStream outs = new ZipOutputStream(new FileOutputStream(descFile));) {
ZipOutputStream zouts = new ZipOutputStream(new FileOutputStream(descFile));
if ("*".equals(fileName) || StringUtils.EMPTY.equals(fileName)) { if ("*".equals(fileName) || StringUtils.EMPTY.equals(fileName)) {
FileUtils.zipDirectoryToZipFile(dirPath, fileDir, zouts); FileUtils.zipDirectoryToZipFile(dirPath, fileDir, outs);
} else { } else {
File file = new File(fileDir, fileName); File file = new File(fileDir, fileName);
if (file.isFile()) { if (file.isFile()) {
FileUtils.zipFilesToZipFile(dirPath, file, zouts); FileUtils.zipFilesToZipFile(dirPath, file, outs);
} else { } else {
FileUtils.zipDirectoryToZipFile(dirPath, file, zouts); FileUtils.zipDirectoryToZipFile(dirPath, file, outs);
} }
} }
zouts.close(); logger.debug("{} 文件压缩成功!", descFileName);
logger.debug(descFileName + " 文件压缩成功!");
} catch (Exception e) { } catch (Exception e) {
logger.debug("文件压缩失败" + e.getMessage()); logger.error("文件压缩失败!", e);
e.printStackTrace();
} }
} }
@@ -511,9 +477,10 @@ public class FileUtils extends org.apache.commons.io.FileUtils {
if (!descFileNames.endsWith(File.separator)) { if (!descFileNames.endsWith(File.separator)) {
descFileNames = descFileNames + File.separator; descFileNames = descFileNames + File.separator;
} }
try { try (
// 根据ZIP文件创建ZipFile对象 // 根据ZIP文件创建ZipFile对象
ZipFile zipFile = new ZipFile(zipFileName); ZipFile zipFile = new ZipFile(zipFileName);
) {
ZipEntry entry = null; ZipEntry entry = null;
String entryName = null; String entryName = null;
String descFileDir = null; String descFileDir = null;
@@ -537,21 +504,21 @@ public class FileUtils extends org.apache.commons.io.FileUtils {
new File(descFileDir).getParentFile().mkdirs(); new File(descFileDir).getParentFile().mkdirs();
} }
File file = new File(descFileDir); File file = new File(descFileDir);
try (
// 打开文件输出流 // 打开文件输出流
OutputStream os = new FileOutputStream(file); OutputStream os = new FileOutputStream(file);
// 从ZipFile对象中打开entry的输入流 // 从ZipFile对象中打开entry的输入流
InputStream is = zipFile.getInputStream(entry); InputStream is = zipFile.getInputStream(entry);
) {
while ((readByte = is.read(buf)) != -1) { while ((readByte = is.read(buf)) != -1) {
os.write(buf, 0, readByte); os.write(buf, 0, readByte);
} }
os.close();
is.close();
} }
zipFile.close(); }
logger.debug("文件解压成功!"); logger.debug("文件解压成功!");
return true; return true;
} catch (Exception e) { } catch (Exception e) {
logger.debug("文件解压失败" + e.getMessage()); logger.error("文件解压失败!", e);
return false; return false;
} }
} }
@@ -566,25 +533,26 @@ public class FileUtils extends org.apache.commons.io.FileUtils {
if (fileDir.isDirectory()) { if (fileDir.isDirectory()) {
File[] files = fileDir.listFiles(); File[] files = fileDir.listFiles();
// 空的文件夹 // 空的文件夹
if (files.length == 0) { if (files != null && files.length == 0) {
// 目录信息 // 目录信息
ZipEntry entry = new ZipEntry(getEntryName(dirPath, fileDir)); ZipEntry entry = new ZipEntry(getEntryName(dirPath, fileDir));
try { try {
zouts.putNextEntry(entry); zouts.putNextEntry(entry);
zouts.closeEntry(); zouts.closeEntry();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); logger.error("压缩失败!", e);
} }
return; return;
} }
if (files != null) {
for (int i = 0; i < files.length; i++) { for (File file : files) {
if (files[i].isFile()) { if (file.isFile()) {
// 如果是文件,则调用文件压缩方法 // 如果是文件,则调用文件压缩方法
FileUtils.zipFilesToZipFile(dirPath, files[i], zouts); FileUtils.zipFilesToZipFile(dirPath, file, zouts);
} else { } else {
// 如果是目录,则递归调用 // 如果是目录,则递归调用
FileUtils.zipDirectoryToZipFile(dirPath, files[i], zouts); FileUtils.zipDirectoryToZipFile(dirPath, file, zouts);
}
} }
} }
} }
@@ -597,17 +565,16 @@ public class FileUtils extends org.apache.commons.io.FileUtils {
* @param zouts 输出流 * @param zouts 输出流
*/ */
public static void zipFilesToZipFile(String dirPath, File file, ZipOutputStream zouts) { public static void zipFilesToZipFile(String dirPath, File file, ZipOutputStream zouts) {
FileInputStream fin = null;
ZipEntry entry = null;
// 创建复制缓冲区 // 创建复制缓冲区
byte[] buf = new byte[4096]; byte[] buf = new byte[4096];
int readByte = 0; int readByte = 0;
if (file.isFile()) { if (file.isFile()) {
try { try (
// 创建一个文件输入流 // 创建一个文件输入流
fin = new FileInputStream(file); FileInputStream fin = new FileInputStream(file);
) {
// 创建一个ZipEntry // 创建一个ZipEntry
entry = new ZipEntry(getEntryName(dirPath, file)); ZipEntry entry = new ZipEntry(getEntryName(dirPath, file));
// 存储信息到压缩文件 // 存储信息到压缩文件
zouts.putNextEntry(entry); zouts.putNextEntry(entry);
// 复制字节到压缩文件 // 复制字节到压缩文件
@@ -615,10 +582,9 @@ public class FileUtils extends org.apache.commons.io.FileUtils {
zouts.write(buf, 0, readByte); zouts.write(buf, 0, readByte);
} }
zouts.closeEntry(); zouts.closeEntry();
fin.close(); logger.debug("添加文件 {} 到zip文件中!", file.getAbsolutePath());
logger.debug("添加文件 " + file.getAbsolutePath() + " 到zip文件中!");
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); logger.error("添加文件失败!", e);
} }
} }
} }
@@ -627,7 +593,7 @@ public class FileUtils extends org.apache.commons.io.FileUtils {
* 获取待压缩文件在ZIP文件中entry的名字即相对于跟目录的相对路径名 * 获取待压缩文件在ZIP文件中entry的名字即相对于跟目录的相对路径名
* @param dirPath 目录名 * @param dirPath 目录名
* @param file entry文件名 * @param file entry文件名
* @return * @return entry名字
*/ */
private static String getEntryName(String dirPath, File file) { private static String getEntryName(String dirPath, File file) {
String dirPaths = dirPath; String dirPaths = dirPath;
@@ -842,8 +808,8 @@ public class FileUtils extends org.apache.commons.io.FileUtils {
/** /**
* 根据图片Base64获取文件扩展名 * 根据图片Base64获取文件扩展名
* @param imageBase64 * @param imageBase64 图片编码内容
* @return * @return 图片文件的扩展名
* @author ThinkGem * @author ThinkGem
*/ */
public static String getFileExtensionByImageBase64(String imageBase64){ public static String getFileExtensionByImageBase64(String imageBase64){
@@ -861,13 +827,11 @@ public class FileUtils extends org.apache.commons.io.FileUtils {
/** /**
* 获取工程源文件所在路径 * 获取工程源文件所在路径
* @return
*/ */
public static String getProjectPath(){ public static String getProjectPath(){
String projectPath = ""; String projectPath = "";
try { try {
File file = ResourceUtils.getResource("").getFile(); File file = ResourceUtils.getResource("").getFile();
if (file != null){
while (true) { while (true) {
File f = new File(path(file.getPath() + "/src/main")); File f = new File(path(file.getPath() + "/src/main"));
if (f.exists()) { if (f.exists()) {
@@ -885,9 +849,6 @@ public class FileUtils extends org.apache.commons.io.FileUtils {
} }
} }
projectPath = file.toString(); projectPath = file.toString();
}
} catch (FileNotFoundException e) {
// 忽略异常
} catch (IOException e) { } catch (IOException e) {
// 忽略异常 // 忽略异常
} }
@@ -900,13 +861,11 @@ public class FileUtils extends org.apache.commons.io.FileUtils {
/** /**
* 获取工程源文件所在路径 * 获取工程源文件所在路径
* @return
*/ */
public static String getWebappPath(){ public static String getWebappPath(){
String webappPath = ""; String webappPath = "";
try { try {
File file = ResourceUtils.getResource("").getFile(); File file = ResourceUtils.getResource("").getFile();
if (file != null){
while (true) { while (true) {
File f = new File(path(file.getPath() + "/WEB-INF/classes")); File f = new File(path(file.getPath() + "/WEB-INF/classes"));
if (f.exists()) { if (f.exists()) {
@@ -924,9 +883,6 @@ public class FileUtils extends org.apache.commons.io.FileUtils {
} }
} }
webappPath = file.toString(); webappPath = file.toString();
}
} catch (FileNotFoundException e) {
// 忽略异常
} catch (IOException e) { } catch (IOException e) {
// 忽略异常 // 忽略异常
} }

View File

@@ -4,6 +4,9 @@
*/ */
package com.jeesite.common.io; package com.jeesite.common.io;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Closeable; import java.io.Closeable;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
@@ -15,71 +18,70 @@ import java.io.InputStream;
/** /**
* 数据流工具类 * 数据流工具类
* @author ThinkGem * @author ThinkGem
* @version 2025-08-08
*/ */
public class IOUtils extends org.apache.commons.io.IOUtils { public class IOUtils extends org.apache.commons.io.IOUtils {
private static final Logger logger = LoggerFactory.getLogger(IOUtils.class);
/** /**
* 根据文件路径创建文件输入流处理 以字节为单位(非 unicode * 根据文件路径创建文件输入流处理 以字节为单位(非 unicode
* @param filePath * @param filePath 文件路径
* @return * @return 文件流
*/ */
public static FileInputStream getFileInputStream(String filePath) { public static FileInputStream getFileInputStream(String filePath) {
FileInputStream fileInputStream = null; FileInputStream fileInputStream = null;
try { try {
fileInputStream = new FileInputStream(filePath); fileInputStream = new FileInputStream(filePath);
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
System.out.println("错误信息:文件不存在"); logger.error("文件不存在!", e);
e.printStackTrace();
} }
return fileInputStream; return fileInputStream;
} }
/** /**
* 根据文件对象创建文件输入流处理 以字节为单位(非 unicode * 根据文件对象创建文件输入流处理 以字节为单位(非 unicode
* @param file * @param file 文件对象
* @return * @return 文件流
*/ */
public static FileInputStream getFileInputStream(File file) { public static FileInputStream getFileInputStream(File file) {
FileInputStream fileInputStream = null; FileInputStream fileInputStream = null;
try { try {
fileInputStream = new FileInputStream(file); fileInputStream = new FileInputStream(file);
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
System.out.println("错误信息:文件不存在"); logger.error("文件不存在!", e);
e.printStackTrace();
} }
return fileInputStream; return fileInputStream;
} }
/** /**
* 根据文件对象创建文件输出流处理 以字节为单位(非 unicode * 根据文件对象创建文件输出流处理 以字节为单位(非 unicode
* @param file * @param file 文件对象
* @param append true:文件以追加方式打开,false:则覆盖原文件的内容 * @param append true:文件以追加方式打开,false:则覆盖原文件的内容
* @return * @return 文件流
*/ */
public static FileOutputStream getFileOutputStream(File file, boolean append) { public static FileOutputStream getFileOutputStream(File file, boolean append) {
FileOutputStream fileOutputStream = null; FileOutputStream fileOutputStream = null;
try { try {
fileOutputStream = new FileOutputStream(file, append); fileOutputStream = new FileOutputStream(file, append);
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
System.out.println("错误信息:文件不存在"); logger.error("文件不存在!", e);
e.printStackTrace();
} }
return fileOutputStream; return fileOutputStream;
} }
/** /**
* 根据文件路径创建文件输出流处理 以字节为单位(非 unicode * 根据文件路径创建文件输出流处理 以字节为单位(非 unicode
* @param filePath * @param filePath 文件路径
* @param append true:文件以追加方式打开,false:则覆盖原文件的内容 * @param append true:文件以追加方式打开,false:则覆盖原文件的内容
* @return * @return 文件流
*/ */
public static FileOutputStream getFileOutputStream(String filePath, boolean append) { public static FileOutputStream getFileOutputStream(String filePath, boolean append) {
FileOutputStream fileOutputStream = null; FileOutputStream fileOutputStream = null;
try { try {
fileOutputStream = new FileOutputStream(filePath, append); fileOutputStream = new FileOutputStream(filePath, append);
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
System.out.println("错误信息:文件不存在"); logger.error("文件不存在!", e);
e.printStackTrace();
} }
return fileOutputStream; return fileOutputStream;
} }

View File

@@ -30,16 +30,14 @@ import java.util.regex.Pattern;
* 相同的属性在最后载入的文件中的值将会覆盖之前的值, * 相同的属性在最后载入的文件中的值将会覆盖之前的值,
* 取不到从System.getProperty()获取。 * 取不到从System.getProperty()获取。
* @author ThinkGem * @author ThinkGem
* @version 2017-12-30 * @version 2025-4-17
*/ */
public class PropertiesUtils { public class PropertiesUtils {
// 默认加载的文件可通过继承覆盖若有相同Key优先加载后面的 // 默认加载的文件可通过继承覆盖若有相同Key优先加载后面的
public static final String[] DEFAULT_CONFIG_FILE = new String[]{ public static final String[] DEFAULT_CONFIG_FILE = new String[]{
"classpath:config/application.yml", "classpath:application.yml", "classpath:config/application.yml", "classpath:application.yml",
"classpath:config/bootstrap.yml", "classpath:bootstrap.yml",
"file:config/application.yml", "file:application.yml", "file:config/application.yml", "file:application.yml",
"file:config/bootstrap.yml", "file:bootstrap.yml",
}; };
private static final Logger logger = PropertiesUtils.initLogger(); private static final Logger logger = PropertiesUtils.initLogger();

View File

@@ -15,7 +15,7 @@ import java.util.Date;
/** /**
* 日期工具类, 继承org.apache.commons.lang.time.DateUtils类 * 日期工具类, 继承org.apache.commons.lang.time.DateUtils类
* @author ThinkGem * @author ThinkGem
* @version 2017-1-4 * @version 2025-08-08
*/ */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils { public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
@@ -179,8 +179,7 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
/** /**
* 获取过去的天数 * 获取过去的天数
* @param date * @param date 日期
* @return
*/ */
public static long pastDays(Date date) { public static long pastDays(Date date) {
long t = System.currentTimeMillis()-date.getTime(); long t = System.currentTimeMillis()-date.getTime();
@@ -189,8 +188,7 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
/** /**
* 获取过去的小时 * 获取过去的小时
* @param date * @param date 日期
* @return
*/ */
public static long pastHour(Date date) { public static long pastHour(Date date) {
long t = System.currentTimeMillis()-date.getTime(); long t = System.currentTimeMillis()-date.getTime();
@@ -199,8 +197,7 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
/** /**
* 获取过去的分钟 * 获取过去的分钟
* @param date * @param date 日期
* @return
*/ */
public static long pastMinutes(Date date) { public static long pastMinutes(Date date) {
long t = System.currentTimeMillis()-date.getTime(); long t = System.currentTimeMillis()-date.getTime();
@@ -209,15 +206,13 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
/** /**
* 获取两个日期之间的天数 * 获取两个日期之间的天数
* * @param before 开始日期
* @param before * @param after 结束日期
* @param after
* @return
*/ */
public static double getDistanceOfTwoDate(Date before, Date after) { public static double getDistanceOfTwoDate(Date before, Date after) {
long beforeTime = before.getTime(); long beforeTime = before.getTime();
long afterTime = after.getTime(); long afterTime = after.getTime();
return (afterTime - beforeTime) / (1000 * 60 * 60 * 24); return (double) (afterTime - beforeTime) / (1000 * 60 * 60 * 24);
} }
/** /**
@@ -250,8 +245,7 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
/** /**
* 获取日期是当年的第几周 * 获取日期是当年的第几周
* @param date * @param date 日期
* @return
*/ */
public static int getWeekOfYear(Date date){ public static int getWeekOfYear(Date date){
Calendar cal = Calendar.getInstance(LocaleUtils.getTimeZone(), LocaleUtils.getLocale()); Calendar cal = Calendar.getInstance(LocaleUtils.getTimeZone(), LocaleUtils.getLocale());
@@ -262,7 +256,6 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
/** /**
* 获取一天的开始时间2015-11-3 00:00:00.000 * 获取一天的开始时间2015-11-3 00:00:00.000
* @param date 日期 * @param date 日期
* @return
*/ */
public static Date getOfDayFirst(Date date) { public static Date getOfDayFirst(Date date) {
if (date == null){ if (date == null){
@@ -280,7 +273,6 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
/** /**
* 获取一天的最后时间2015-11-3 23:59:59.999 * 获取一天的最后时间2015-11-3 23:59:59.999
* @param date 日期 * @param date 日期
* @return
*/ */
public static Date getOfDayLast(Date date) { public static Date getOfDayLast(Date date) {
if (date == null){ if (date == null){
@@ -297,7 +289,6 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
/** /**
* 获取服务器启动时间 * 获取服务器启动时间
* @return
*/ */
public static Date getServerStartDate(){ public static Date getServerStartDate(){
long time = ManagementFactory.getRuntimeMXBean().getStartTime(); long time = ManagementFactory.getRuntimeMXBean().getStartTime();

View File

@@ -19,8 +19,7 @@ public class ExceptionUtils {
/** /**
* 在request中获取异常类 * 在request中获取异常类
* @param request * @param request 请求对象
* @return
*/ */
public static Throwable getThrowable(HttpServletRequest request){ public static Throwable getThrowable(HttpServletRequest request){
Throwable ex = null; Throwable ex = null;

View File

@@ -79,7 +79,6 @@ public class NumberUtils extends org.apache.commons.lang3.math.NumberUtils {
/** /**
* 格式化双精度,保留两个小数 * 格式化双精度,保留两个小数
* @return
*/ */
public static String formatDouble(Double b) { public static String formatDouble(Double b) {
BigDecimal bg = new BigDecimal(b); BigDecimal bg = new BigDecimal(b);
@@ -88,7 +87,6 @@ public class NumberUtils extends org.apache.commons.lang3.math.NumberUtils {
/** /**
* 百分比计算 * 百分比计算
* @return
*/ */
public static String formatScale(double one, long total) { public static String formatScale(double one, long total) {
BigDecimal bg = new BigDecimal(one * 100 / total); BigDecimal bg = new BigDecimal(one * 100 / total);
@@ -97,8 +95,6 @@ public class NumberUtils extends org.apache.commons.lang3.math.NumberUtils {
/** /**
* 格式化数值类型 * 格式化数值类型
* @param data
* @param pattern
*/ */
public static String formatNumber(Object data, String pattern) { public static String formatNumber(Object data, String pattern) {
if (data == null){ if (data == null){

View File

@@ -21,7 +21,7 @@ import java.util.List;
*/ */
public class VideoUtils { public class VideoUtils {
private static final Logger log = LoggerFactory.getLogger(VideoUtils.class); private static final Logger logger = LoggerFactory.getLogger(VideoUtils.class);
private static String ffmpegFile; // ffmpeg.exe所放的路径 private static String ffmpegFile; // ffmpeg.exe所放的路径
private static String mencoderFile; // mencoder.exe所放的路径 private static String mencoderFile; // mencoder.exe所放的路径
private static String qtFaststartFile; // qt-faststart.exe所放的路径 private static String qtFaststartFile; // qt-faststart.exe所放的路径
@@ -111,10 +111,10 @@ public class VideoUtils {
} }
} catch (Exception e) { } catch (Exception e) {
statusTemp = false; statusTemp = false;
log.error("视频剪切图片失败", e); logger.error("视频剪切图片失败", e);
} }
} }
log.debug("视频剪切图片" + (statusTemp ? "成功" : "失败") + ",用时:" + TimeUtils.formatTime(System.currentTimeMillis() - startTime)); logger.debug("视频剪切图片" + (statusTemp ? "成功" : "失败") + ",用时:" + TimeUtils.formatTime(System.currentTimeMillis() - startTime));
return statusTemp; return statusTemp;
} }
@@ -128,19 +128,19 @@ public class VideoUtils {
int type = checkContentType(); int type = checkContentType();
String tempFile = outputFile + ".tmp"; String tempFile = outputFile + ".tmp";
if (statusTemp && type == 0) { if (statusTemp && type == 0) {
log.debug("使用ffmpage进行视频转换"); logger.debug("使用ffmpage进行视频转换");
statusTemp = processFfmpeg(inputFile, tempFile); statusTemp = processFfmpeg(inputFile, tempFile);
} else if (statusTemp && type == 1) { } else if (statusTemp && type == 1) {
log.debug("使用mencoder进行视频转换"); logger.debug("使用mencoder进行视频转换");
statusTemp = processMencoder(inputFile, tempFile); statusTemp = processMencoder(inputFile, tempFile);
} }
if (statusTemp){ if (statusTemp){
log.debug("将mp4视频的元数据信息转到视频第一帧"); logger.debug("将mp4视频的元数据信息转到视频第一帧");
statusTemp = processQtFaststart(tempFile, outputFile); statusTemp = processQtFaststart(tempFile, outputFile);
} }
log.debug("删除临时文件"); logger.debug("删除临时文件");
FileUtils.deleteFile(tempFile); FileUtils.deleteFile(tempFile);
log.debug("视频转换" + (statusTemp ? "成功" : "失败") + ",用时:" + TimeUtils.formatTime(System.currentTimeMillis() - startTime)); logger.debug("视频转换{},用时:{}", statusTemp ? "成功" : "失败", TimeUtils.formatTime(System.currentTimeMillis() - startTime));
return statusTemp; return statusTemp;
} }
@@ -152,7 +152,7 @@ public class VideoUtils {
public boolean checkfile(String inputFile) { public boolean checkfile(String inputFile) {
File file = new File(inputFile); File file = new File(inputFile);
if (!file.isFile() || !file.exists()) { if (!file.isFile() || !file.exists()) {
log.warn("文件不存在!"); logger.warn("文件不存在!");
return false; return false;
} }
return true; return true;
@@ -279,18 +279,18 @@ public class VideoUtils {
*/ */
private boolean process(List<String> command) { private boolean process(List<String> command) {
try { try {
log.debug(StringUtils.join(command, StringUtils.SPACE)); logger.debug(StringUtils.join(command, StringUtils.SPACE));
// Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); // Process process = new ProcessBuilder(command).redirectErrorStream(true).start();
Process process = Runtime.getRuntime().exec(command.toArray(new String[command.size()])); Process process = Runtime.getRuntime().exec(command.toArray(new String[0]));
new PrintErrorReader(process.getErrorStream()).start(); new PrintErrorReader(process.getErrorStream()).start();
new PrintInputStream(process.getInputStream()).start(); new PrintInputStream(process.getInputStream()).start();
process.waitFor(); process.waitFor();
return true; return true;
} catch (Exception e) { } catch (Exception e) {
if (StringUtils.contains(e.getMessage(), "CreateProcess error=2")){ if (StringUtils.contains(e.getMessage(), "CreateProcess error=2")){
log.error("缺少视频转换工具请配置video.ffmpegFile相关参数。" + e.getMessage()); logger.error("缺少视频转换工具请配置video.ffmpegFile相关参数。{}", e.getMessage());
}else{ }else{
log.error(e.getMessage(), e); logger.error(e.getMessage(), e);
} }
return false; return false;
} }
@@ -406,10 +406,10 @@ public class VideoUtils {
BufferedReader br = new BufferedReader(new InputStreamReader(__is)); BufferedReader br = new BufferedReader(new InputStreamReader(__is));
String line = null; String line = null;
while ((line = br.readLine()) != null) { while ((line = br.readLine()) != null) {
log.debug(line); logger.debug(line);
} }
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); logger.error(e.getMessage(), e);
} }
} }
} }
@@ -427,10 +427,10 @@ public class VideoUtils {
BufferedReader br = new BufferedReader(new InputStreamReader(__is)); BufferedReader br = new BufferedReader(new InputStreamReader(__is));
String line = null; String line = null;
while ((line = br.readLine()) != null) { while ((line = br.readLine()) != null) {
log.error(line); logger.error(line);
} }
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); logger.error(e.getMessage(), e);
} }
} }
} }

View File

@@ -13,6 +13,7 @@ import com.jeesite.common.io.PropertiesUtils;
/** /**
* 发送电子邮件 * 发送电子邮件
* @author ThinkGem
*/ */
public class EmailUtils { public class EmailUtils {

View File

@@ -1,3 +1,7 @@
/**
* Copyright (c) 2013-Now http://jeesite.com All rights reserved.
* No deletion without permission, or be held responsible to law.
*/
package com.jeesite.common.msg; package com.jeesite.common.msg;
import org.slf4j.Logger; import org.slf4j.Logger;
@@ -5,6 +9,7 @@ import org.slf4j.LoggerFactory;
/** /**
* 发送短信请实现send方法 * 发送短信请实现send方法
* @author ThinkGem
*/ */
public class SmsUtils { public class SmsUtils {

View File

@@ -1,3 +1,7 @@
/**
* Copyright (c) 2013-Now http://jeesite.com All rights reserved.
* No deletion without permission, or be held responsible to law.
*/
package com.jeesite.common.network; package com.jeesite.common.network;
import com.jeesite.common.codec.EncodeUtils; import com.jeesite.common.codec.EncodeUtils;
@@ -6,12 +10,15 @@ import com.jeesite.common.lang.StringUtils;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
/**
* IP 地址工具
* @author ThinkGem
*/
public class IpUtils { public class IpUtils {
/** /**
* 获取客户端IP地址 * 获取客户端IP地址
* @param request * @param request 请求对象
* @return
*/ */
public static String getRemoteAddr(HttpServletRequest request) { public static String getRemoteAddr(HttpServletRequest request) {
if (request == null) { if (request == null) {
@@ -38,8 +45,7 @@ public class IpUtils {
/** /**
* 是否是本地地址 * 是否是本地地址
* @param ip * @param ip 地址
* @return
*/ */
public static boolean isLocalAddr(String ip){ public static boolean isLocalAddr(String ip){
return StringUtils.inString(ip, "127.0.0.1", "0:0:0:0:0:0:0:1"); return StringUtils.inString(ip, "127.0.0.1", "0:0:0:0:0:0:0:1");
@@ -47,13 +53,12 @@ public class IpUtils {
/** /**
* 判断IP地址为内网IP还是公网IP * 判断IP地址为内网IP还是公网IP
* * <br>
* tcp/ip协议中专门保留了三个IP地址区域作为私有地址其地址范围如下 * tcp/ip协议中专门保留了三个IP地址区域作为私有地址其地址范围如下
* 10.0.0.0/810.0.0.010.255.255.255 * 10.0.0.0/810.0.0.010.255.255.255
* 172.16.0.0/12172.16.0.0172.31.255.255 * 172.16.0.0/12172.16.0.0172.31.255.255
* 192.168.0.0/16192.168.0.0192.168.255.255 * 192.168.0.0/16192.168.0.0192.168.255.255
* * @param ip 地址
* @param ip
* @return * @return
*/ */
public static boolean isInternalAddr(String ip) { public static boolean isInternalAddr(String ip) {

View File

@@ -4,18 +4,22 @@
*/ */
package com.jeesite.common.network; package com.jeesite.common.network;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.IOException; import java.io.IOException;
import java.io.InputStreamReader; import java.io.InputStreamReader;
/** /**
* MAC地址工具 * MAC地址工具
*
* @author ThinkGem * @author ThinkGem
* @version 2014-6-18 * @version 2014-6-18
*/ */
public class MacUtils { public class MacUtils {
private static final Logger logger = LoggerFactory.getLogger(MacUtils.class);
/** /**
* 获取当前操作系统名称. return 操作系统名称 例如:windows,Linux,Unix等. * 获取当前操作系统名称. return 操作系统名称 例如:windows,Linux,Unix等.
*/ */
@@ -25,7 +29,6 @@ public class MacUtils {
/** /**
* 获取Unix网卡的mac地址. * 获取Unix网卡的mac地址.
*
* @return mac地址 * @return mac地址
*/ */
public static String getUnixMACAddress() { public static String getUnixMACAddress() {
@@ -33,39 +36,31 @@ public class MacUtils {
BufferedReader bufferedReader = null; BufferedReader bufferedReader = null;
Process process = null; Process process = null;
try { try {
/** // Unix下的命令一般取eth0作为本地主网卡 显示信息中包含有mac地址信息
* Unix下的命令一般取eth0作为本地主网卡 显示信息中包含有mac地址信息
*/
process = Runtime.getRuntime().exec("ifconfig eth0"); process = Runtime.getRuntime().exec("ifconfig eth0");
bufferedReader = new BufferedReader(new InputStreamReader( bufferedReader = new BufferedReader(new InputStreamReader(
process.getInputStream())); process.getInputStream()));
String line = null; String line = null;
int index = -1; int index = -1;
while ((line = bufferedReader.readLine()) != null) { while ((line = bufferedReader.readLine()) != null) {
/** // 寻找标示字符串[hwaddr]
* 寻找标示字符串[hwaddr]
*/
index = line.toLowerCase().indexOf("hwaddr"); index = line.toLowerCase().indexOf("hwaddr");
/** // 找到了
* 找到了
*/
if (index != -1) { if (index != -1) {
/** // 取出mac地址并去除2边空格
* 取出mac地址并去除2边空格
*/
mac = line.substring(index + "hwaddr".length() + 1).trim(); mac = line.substring(index + "hwaddr".length() + 1).trim();
break; break;
} }
} }
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); logger.error(e.getMessage());
} finally { } finally {
try { try {
if (bufferedReader != null) { if (bufferedReader != null) {
bufferedReader.close(); bufferedReader.close();
} }
} catch (IOException e1) { } catch (IOException e1) {
e1.printStackTrace(); // ignore
} }
bufferedReader = null; bufferedReader = null;
process = null; process = null;
@@ -84,9 +79,7 @@ public class MacUtils {
BufferedReader bufferedReader = null; BufferedReader bufferedReader = null;
Process process = null; Process process = null;
try { try {
/** // linux下的命令一般取eth0作为本地主网卡 显示信息中包含有mac地址信息
* linux下的命令一般取eth0作为本地主网卡 显示信息中包含有mac地址信息
*/
process = Runtime.getRuntime().exec("ifconfig eth0"); process = Runtime.getRuntime().exec("ifconfig eth0");
bufferedReader = new BufferedReader(new InputStreamReader( bufferedReader = new BufferedReader(new InputStreamReader(
process.getInputStream())); process.getInputStream()));
@@ -94,26 +87,22 @@ public class MacUtils {
int index = -1; int index = -1;
while ((line = bufferedReader.readLine()) != null) { while ((line = bufferedReader.readLine()) != null) {
index = line.toLowerCase().indexOf("硬件地址"); index = line.toLowerCase().indexOf("硬件地址");
/** // 找到了
* 找到了
*/
if (index != -1) { if (index != -1) {
/** // 取出mac地址并去除2边空格
* 取出mac地址并去除2边空格
*/
mac = line.substring(index + 4).trim(); mac = line.substring(index + 4).trim();
break; break;
} }
} }
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); logger.error(e.getMessage());
} finally { } finally {
try { try {
if (bufferedReader != null) { if (bufferedReader != null) {
bufferedReader.close(); bufferedReader.close();
} }
} catch (IOException e1) { } catch (IOException e1) {
e1.printStackTrace(); // ignore
} }
bufferedReader = null; bufferedReader = null;
process = null; process = null;
@@ -129,7 +118,6 @@ public class MacUtils {
/** /**
* 获取widnows网卡的mac地址. * 获取widnows网卡的mac地址.
*
* @return mac地址 * @return mac地址
*/ */
public static String getWindowsMACAddress() { public static String getWindowsMACAddress() {
@@ -137,37 +125,31 @@ public class MacUtils {
BufferedReader bufferedReader = null; BufferedReader bufferedReader = null;
Process process = null; Process process = null;
try { try {
/** // windows下的命令显示信息中包含有mac地址信息
* windows下的命令显示信息中包含有mac地址信息
*/
process = Runtime.getRuntime().exec("ipconfig /all"); process = Runtime.getRuntime().exec("ipconfig /all");
bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream())); bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null; String line = null;
int index = -1; int index = -1;
while ((line = bufferedReader.readLine()) != null) { while ((line = bufferedReader.readLine()) != null) {
/** // 寻找标示字符串[physical address 或 物理地址]
* 寻找标示字符串[physical address 或 物理地址]
*/
if (line.split("-").length == 6){ if (line.split("-").length == 6){
index = line.indexOf(":"); index = line.indexOf(":");
if (index != -1) { if (index != -1) {
/** // 取出mac地址并去除2边空格
* 取出mac地址并去除2边空格
*/
mac = line.substring(index + 1).trim(); mac = line.substring(index + 1).trim();
} }
break; break;
} }
} }
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); logger.error(e.getMessage());
} finally { } finally {
try { try {
if (bufferedReader != null) { if (bufferedReader != null) {
bufferedReader.close(); bufferedReader.close();
} }
} catch (IOException e1) { } catch (IOException e1) {
e1.printStackTrace(); // ignore
} }
bufferedReader = null; bufferedReader = null;
process = null; process = null;

View File

@@ -21,7 +21,7 @@ import java.util.Map;
/** /**
* 反射工具类. 提供调用getter/setter方法, 访问私有变量, 调用私有方法, 获取泛型类型Class, 被AOP过的真实类等工具函数. * 反射工具类. 提供调用getter/setter方法, 访问私有变量, 调用私有方法, 获取泛型类型Class, 被AOP过的真实类等工具函数.
* @author calvin、ThinkGem * @author calvin、ThinkGem
* @version 2023-2-6 * @version 2025-08-08
*/ */
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
public class ReflectUtils { public class ReflectUtils {
@@ -112,7 +112,7 @@ public class ReflectUtils {
if (field == null) { if (field == null) {
//throw new IllegalArgumentException("在 [" + obj.getClass() + "] 中,没有找到 [" + fieldName + "] 字段 "); //throw new IllegalArgumentException("在 [" + obj.getClass() + "] 中,没有找到 [" + fieldName + "] 字段 ");
if (obj != null) { if (obj != null) {
logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + fieldName + "] 字段 "); logger.debug("在 [{}] 中,没有找到 [{}] 字段 ", obj.getClass(), fieldName);
} }
return null; return null;
} }
@@ -132,7 +132,7 @@ public class ReflectUtils {
Field field = getAccessibleField(obj, fieldName); Field field = getAccessibleField(obj, fieldName);
if (field == null) { if (field == null) {
//throw new IllegalArgumentException("在 [" + obj.getClass() + "] 中,没有找到 [" + fieldName + "] 字段 "); //throw new IllegalArgumentException("在 [" + obj.getClass() + "] 中,没有找到 [" + fieldName + "] 字段 ");
logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + fieldName + "] 字段 "); logger.debug("在 [{}] 中,没有找到 [{}] 字段 ", obj.getClass(), fieldName);
return; return;
} }
try { try {
@@ -157,9 +157,7 @@ public class ReflectUtils {
Method method = getAccessibleMethod(obj, methodName, parameterTypes); Method method = getAccessibleMethod(obj, methodName, parameterTypes);
if (method == null) { if (method == null) {
//throw new IllegalArgumentException("在 [" + obj.getClass() + "] 中,没有找到 [" + methodName + "] 方法 "); //throw new IllegalArgumentException("在 [" + obj.getClass() + "] 中,没有找到 [" + methodName + "] 方法 ");
if (obj != null) { logger.debug("在 [{}] 中,没有找到 [{}] 方法 ", obj.getClass() == Class.class ? obj : obj.getClass(), methodName);
logger.debug("在 [" + (obj.getClass() == Class.class ? obj : obj.getClass()) + "] 中,没有找到 [" + methodName + "] 方法 ");
}
return null; return null;
} }
try { try {
@@ -182,7 +180,7 @@ public class ReflectUtils {
if (method == null) { if (method == null) {
// 如果为空不报错,直接返回空。 throw new IllegalArgumentException("在 [" + obj.getClass() + "] 中,没有找到 [" + methodName + "] 方法 "); // 如果为空不报错,直接返回空。 throw new IllegalArgumentException("在 [" + obj.getClass() + "] 中,没有找到 [" + methodName + "] 方法 ");
if (obj != null) { if (obj != null) {
logger.debug("在 [" + (obj.getClass() == Class.class ? obj : obj.getClass()) + "] 中,没有找到 [" + methodName + "] 方法 "); logger.debug("在 [{}] 中,没有找到 [{}] 方法 ", obj.getClass() == Class.class ? obj : obj.getClass(), methodName);
} }
return null; return null;
} }
@@ -405,17 +403,16 @@ public class ReflectUtils {
public static Class getClassGenricType(final Class clazz, final int index) { public static Class getClassGenricType(final Class clazz, final int index) {
Type genType = clazz.getGenericSuperclass(); Type genType = clazz.getGenericSuperclass();
if (!(genType instanceof ParameterizedType)) { if (!(genType instanceof ParameterizedType)) {
logger.debug(clazz.getSimpleName() + "'s superclass not ParameterizedType"); logger.debug("{}'s superclass not ParameterizedType", clazz.getSimpleName());
return Object.class; return Object.class;
} }
Type[] params = ((ParameterizedType) genType).getActualTypeArguments(); Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
if (index >= params.length || index < 0) { if (index >= params.length || index < 0) {
logger.debug("Index: " + index + ", Size of " + clazz.getSimpleName() + "'s Parameterized Type: " logger.debug("Index: {}, Size of {}'s Parameterized Type: {}", index, clazz.getSimpleName(), params.length);
+ params.length);
return Object.class; return Object.class;
} }
if (!(params[index] instanceof Class)) { if (!(params[index] instanceof Class)) {
logger.debug(clazz.getSimpleName() + " not set the actual class on superclass generic parameter"); logger.debug("{} not set the actual class on superclass generic parameter", clazz.getSimpleName());
return Object.class; return Object.class;
} }
return (Class) params[index]; return (Class) params[index];
@@ -429,7 +426,7 @@ public class ReflectUtils {
throw new RuntimeException("Instance must not be null"); throw new RuntimeException("Instance must not be null");
} }
Class clazz = instance.getClass(); Class clazz = instance.getClass();
if (clazz != null && clazz.getName().contains(CGLIB_CLASS_SEPARATOR)) { if (clazz.getName().contains(CGLIB_CLASS_SEPARATOR)) {
Class<?> superClass = clazz.getSuperclass(); Class<?> superClass = clazz.getSuperclass();
if (superClass != null && !Object.class.equals(superClass)) { if (superClass != null && !Object.class.equals(superClass)) {
return superClass; return superClass;

View File

@@ -1,3 +1,7 @@
/**
* Copyright (c) 2013-Now http://jeesite.com All rights reserved.
* No deletion without permission, or be held responsible to law.
*/
package com.jeesite.common.text; package com.jeesite.common.text;
import net.sourceforge.pinyin4j.PinyinHelper; import net.sourceforge.pinyin4j.PinyinHelper;
@@ -6,6 +10,8 @@ import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType; import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType; import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination; import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.regex.Pattern; import java.util.regex.Pattern;
@@ -15,9 +21,11 @@ import java.util.regex.Pattern;
*/ */
public class PinyinUtils { public class PinyinUtils {
private static final Logger logger = LoggerFactory.getLogger(PinyinUtils.class);
private static class Static{ private static class Static{
private static Pattern idPatt = Pattern.compile("\\W"); private static final Pattern idPat = Pattern.compile("\\W");
private static HanyuPinyinOutputFormat defaultFormat; private static final HanyuPinyinOutputFormat defaultFormat;
static{ static{
defaultFormat = new HanyuPinyinOutputFormat(); defaultFormat = new HanyuPinyinOutputFormat();
defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE); defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
@@ -46,28 +54,28 @@ public class PinyinUtils {
if (chinese == null){ if (chinese == null){
return null; return null;
} }
StringBuffer pybf = new StringBuffer(); StringBuilder sb = new StringBuilder();
char[] arr = chinese.toCharArray(); char[] arr = chinese.toCharArray();
for (int i = 0; i < arr.length; i++) { for (char c : arr) {
if (arr[i] > 128) { if (c > 128) {
try { try {
String[] temp = PinyinHelper.toHanyuPinyinStringArray(arr[i], Static.defaultFormat); String[] temp = PinyinHelper.toHanyuPinyinStringArray(c, Static.defaultFormat);
if (temp != null && temp.length > 0) { if (temp != null && temp.length > 0) {
pybf.append(temp[0].charAt(0)); sb.append(temp[0].charAt(0));
} else { } else {
pybf.append(String.valueOf(arr[i])); sb.append(String.valueOf(c));
} }
} catch (BadHanyuPinyinOutputFormatCombination e) { } catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace(); logger.error(e.getMessage(), e);
} }
} else { } else {
pybf.append(arr[i]); sb.append(c);
} }
} }
if (isId){ if (isId){
return Static.idPatt.matcher(pybf.toString()).replaceAll("").trim(); return Static.idPat.matcher(sb.toString()).replaceAll("").trim();
} }
return pybf.toString(); return sb.toString();
} }
/** /**
@@ -90,28 +98,28 @@ public class PinyinUtils {
if (chinese == null){ if (chinese == null){
return null; return null;
} }
StringBuffer pybf = new StringBuffer(); StringBuilder sb = new StringBuilder();
char[] arr = chinese.toCharArray(); char[] arr = chinese.toCharArray();
for (int i = 0; i < arr.length; i++) { for (char c : arr) {
if (arr[i] > 128) { if (c > 128) {
try { try {
String[] ss = PinyinHelper.toHanyuPinyinStringArray(arr[i], Static.defaultFormat); String[] ss = PinyinHelper.toHanyuPinyinStringArray(c, Static.defaultFormat);
if (ss != null && ss.length > 0) { if (ss != null && ss.length > 0) {
pybf.append(ss[0]); sb.append(ss[0]);
} else { } else {
pybf.append(String.valueOf(arr[i])); sb.append(String.valueOf(c));
} }
} catch (BadHanyuPinyinOutputFormatCombination e) { } catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace(); logger.error(e.getMessage(), e);
} }
} else { } else {
pybf.append(arr[i]); sb.append(c);
} }
} }
if (isId){ if (isId){
return Static.idPatt.matcher(pybf.toString()).replaceAll("").trim(); return Static.idPat.matcher(sb.toString()).replaceAll("").trim();
} }
return pybf.toString(); return sb.toString();
} }
/** /**
@@ -143,7 +151,7 @@ public class PinyinUtils {
if (input == null){ if (input == null){
return null; return null;
} }
char c[] = input.toCharArray(); char[] c = input.toCharArray();
for (int i = 0; i < c.length; i++) { for (int i = 0; i < c.length; i++) {
if (c[i] == '\u3000') { if (c[i] == '\u3000') {
c[i] = ' '; c[i] = ' ';

View File

@@ -27,11 +27,11 @@ public class IdcardUtils {
"62", "63", "64", "65", "71", "81", "82", "91" }; "62", "63", "64", "65", "71", "81", "82", "91" };
/** 每位加权因子 */ /** 每位加权因子 */
public static final int power[] = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, public static final int[] power = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9,
10, 5, 8, 4, 2 }; 10, 5, 8, 4, 2 };
/** 第18位校检码 */ /** 第18位校检码 */
public static final String verifyCode[] = { "1", "0", "X", "9", "8", "7", public static final String[] verifyCode = { "1", "0", "X", "9", "8", "7",
"6", "5", "4", "3", "2" }; "6", "5", "4", "3", "2" };
/** 最低年限 */ /** 最低年限 */
public static final int MIN = 1930; public static final int MIN = 1930;
@@ -116,9 +116,7 @@ public class IdcardUtils {
/** /**
* 将15位身份证号码转换为18位 * 将15位身份证号码转换为18位
* * @param idCard 15位身份编码
* @param idCard
* 15位身份编码
* @return 18位身份编码 * @return 18位身份编码
*/ */
public static String conver15CardTo18(String idCard) { public static String conver15CardTo18(String idCard) {

View File

@@ -22,7 +22,6 @@ public class ThreadUtils {
Thread.sleep(millis); Thread.sleep(millis);
} catch (InterruptedException e) { } catch (InterruptedException e) {
// Ignore. // Ignore.
return;
} }
} }
@@ -34,7 +33,6 @@ public class ThreadUtils {
Thread.sleep(unit.toMillis(duration)); Thread.sleep(unit.toMillis(duration));
} catch (InterruptedException e) { } catch (InterruptedException e) {
// Ignore. // Ignore.
return;
} }
} }

View File

@@ -509,7 +509,7 @@ public class ExcelExport implements Closeable{
cell.setCellStyle(style); cell.setCellStyle(style);
// } // }
} catch (Exception ex) { } catch (Exception ex) {
log.info("Set cell value ["+row.getRowNum()+","+column+"] error: " + ex.toString()); log.info("Set cell value [{},{}] error: {}", row.getRowNum(), column, ex.toString());
cell.setCellValue(ObjectUtils.toString(val)); cell.setCellValue(ObjectUtils.toString(val));
} }
return cell; return cell;
@@ -581,7 +581,7 @@ public class ExcelExport implements Closeable{
this.addCell(row, colunm++, val, ef.align(), ef.fieldType(), ef.dataFormat()); this.addCell(row, colunm++, val, ef.align(), ef.fieldType(), ef.dataFormat());
sb.append(val + ", "); sb.append(val + ", ");
} }
log.debug("Write success: ["+row.getRowNum()+"] "+sb.toString()); log.debug("Write success: [{}] {}", row.getRowNum(), sb.toString());
} }
return this; return this;
} }
@@ -633,7 +633,7 @@ public class ExcelExport implements Closeable{
// try { // try {
// this.close(); // this.close();
// } catch (Exception e) { // } catch (Exception e) {
// e.printStackTrace(); // log.error(e.getMessage(), e);
// } // }
// return this; // return this;
// } // }
@@ -647,7 +647,7 @@ public class ExcelExport implements Closeable{
try { try {
wb.close(); wb.close();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); log.error(e.getMessage(), e);
} }
} }

View File

@@ -465,7 +465,7 @@ public class ExcelImport implements Closeable {
//val = DictUtils.getDictValue(val.toString(), ef.dictType(), ""); //val = DictUtils.getDictValue(val.toString(), ef.dictType(), "");
//log.debug("Dictionary type value: ["+i+","+colunm+"] " + val); //log.debug("Dictionary type value: ["+i+","+colunm+"] " + val);
} catch (Exception ex) { } catch (Exception ex) {
log.info("Get cell value ["+i+","+column+"] error: " + ex.toString()); log.info("Get cell value [{},{}] error: {}", i, column, ex.toString());
val = null; val = null;
} }
} }
@@ -557,7 +557,7 @@ public class ExcelImport implements Closeable {
sb.append(val+", "); sb.append(val+", ");
} }
dataList.add(e); dataList.add(e);
log.debug("Read success: ["+i+"] "+sb.toString()); log.debug("Read success: [{}] {}", i, sb.toString());
} }
return dataList; return dataList;
} }
@@ -577,7 +577,7 @@ public class ExcelImport implements Closeable {
try { try {
wb.close(); wb.close();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); log.error(e.getMessage(), e);
} }
} }

View File

@@ -8,7 +8,6 @@ import org.apache.commons.lang3.StringUtils;
import java.math.BigDecimal; import java.math.BigDecimal;
/** /**
* BigDecimal类型转换 * BigDecimal类型转换
* @author ThinkGem * @author ThinkGem

View File

@@ -9,7 +9,6 @@ import java.text.NumberFormat;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
/** /**
* 金额类型转换(保留两位) * 金额类型转换(保留两位)
* @author ThinkGem * @author ThinkGem

View File

@@ -1,10 +1,17 @@
package com.jeesite.common.utils.word; package com.jeesite.common.utils.word;
import java.io.File; import com.jeesite.common.io.ResourceUtils;
import java.io.FileNotFoundException; import org.apache.commons.lang3.StringUtils;
import java.io.FileOutputStream; import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import java.io.IOException; import org.apache.poi.openxml4j.opc.OPCPackage;
import java.io.InputStream; import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTHeight;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTrPr;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Node;
import java.io.*;
import java.math.BigInteger; import java.math.BigInteger;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
@@ -12,22 +19,6 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTHeight;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTrPr;
import org.w3c.dom.Node;
import com.jeesite.common.io.ResourceUtils;
/** /**
* 使用POI,进行Word相关的操作 * 使用POI,进行Word相关的操作
* @author xuyu * @author xuyu
@@ -38,6 +29,8 @@ import com.jeesite.common.io.ResourceUtils;
*/ */
public class WordExport { public class WordExport {
private static final Logger log = LoggerFactory.getLogger(WordExport.class);
/** 内部使用的文档对象 **/ /** 内部使用的文档对象 **/
private XWPFDocument document; private XWPFDocument document;
@@ -57,7 +50,7 @@ public class WordExport {
} }
bookMarks = new BookMarks(document); bookMarks = new BookMarks(document);
} catch (IOException | InvalidFormatException e) { } catch (IOException | InvalidFormatException e) {
e.printStackTrace(); log.error(e.getMessage(), e);
} }
} }
@@ -224,10 +217,8 @@ public class WordExport {
try { try {
fos = new FileOutputStream(newFile); fos = new FileOutputStream(newFile);
this.document.write(fos); this.document.write(fos);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); log.error(e.getMessage(), e);
} finally { } finally {
try { try {
if (fos != null){ if (fos != null){
@@ -237,7 +228,7 @@ public class WordExport {
fos.close(); fos.close();
} }
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); log.error(e.getMessage(), e);
} }
} }
} }

View File

@@ -18,7 +18,7 @@ public class ZxingUtilsTest {
String baseDir = FileUtils.getProjectPath(); String baseDir = FileUtils.getProjectPath();
// 条形码 // 条形码
String imgPath = baseDir + "\\target\\zxing_EAN13.png"; String imgPath = baseDir + "/target/zxing_EAN13.png";
String contents = "6923450657713"; String contents = "6923450657713";
int width = 105, height = 50; int width = 105, height = 50;
@@ -30,7 +30,7 @@ public class ZxingUtilsTest {
System.out.println("finished zxing EAN-13 decode."); System.out.println("finished zxing EAN-13 decode.");
// 二维码 // 二维码
String imgPath2 = baseDir + "\\target\\zxing.png"; String imgPath2 = baseDir + "/target/zxing.png";
String contents2 = "Hello Gem, welcome to Zxing!\nEMail [ thinkgem@163.com ]"; String contents2 = "Hello Gem, welcome to Zxing!\nEMail [ thinkgem@163.com ]";
int width2 = 300, height2 = 300; int width2 = 300, height2 = 300;