├── .gitignore ├── pom.xml └── src └── main └── java └── com └── JUtils ├── QRCode ├── MatrixToImageConfig.java ├── MatrixToImageWriter.java ├── MatrixToImageWriterEx.java └── MatrixToLogoImageConfig.java ├── base ├── ConvertUtils.java ├── IdcardValidator.java ├── MoneyUtils.java ├── RegexUtils.java ├── StringUtils.java └── ValidateHelper.java ├── beanConvert └── BeanMapConvert.java ├── clone └── CloneUtils.java ├── date ├── DateFormatUtils.java ├── DateUtils.java └── TimestampUtils.java ├── encrypt ├── AESUtils.java ├── Base64Utils.java ├── DESUtils.java ├── EncryptAndDecryptUtils.java └── MD5Utils.java ├── excel ├── ExcelExportHelper.java └── ExcelReadHelper.java ├── file ├── FileUtils.java └── ZipUitls.java ├── image └── ImageUtil.java ├── math ├── BigDecimalUtils.java └── RandomUtils.java ├── sensitiveword ├── SensitiveWordInit.java └── SensitivewordFilterUtil.java ├── sequence └── GenerateSequenceUtil.java └── word └── WordExportUtils.java /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | *.iml 3 | **/*.iml 4 | **/target 5 | .idea -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | jutils 8 | jutils 9 | 1.0-SNAPSHOT 10 | 11 | 12 | -------------------------------------------------------------------------------- /src/main/java/com/JUtils/QRCode/MatrixToImageConfig.java: -------------------------------------------------------------------------------- 1 | package com.JUtils.QRCode; 2 | 3 | import java.awt.image.BufferedImage; 4 | 5 | /** 6 | * 7 | */ 8 | public final class MatrixToImageConfig { 9 | 10 | public static final int BLACK = 0xFF000000; 11 | public static final int WHITE = 0xFFFFFFFF; 12 | 13 | private final int onColor; 14 | private final int offColor; 15 | 16 | /** 17 | * Creates a default config with on color {@link #BLACK} and off color {@link #WHITE}, generating normal 18 | * black-on-white barcodes. 19 | */ 20 | public MatrixToImageConfig() { 21 | this(BLACK, WHITE); 22 | } 23 | 24 | /** 25 | * @param onColor pixel on color, specified as an ARGB value as an int 26 | * @param offColor pixel off color, specified as an ARGB value as an int 27 | */ 28 | public MatrixToImageConfig(int onColor, int offColor) { 29 | this.onColor = onColor; 30 | this.offColor = offColor; 31 | } 32 | 33 | public int getPixelOnColor() { 34 | return onColor; 35 | } 36 | 37 | public int getPixelOffColor() { 38 | return offColor; 39 | } 40 | 41 | int getBufferedImageColorModel() { 42 | // Use faster BINARY if colors match default 43 | // return onColor == BLACK && offColor == WHITE ? BufferedImage.TYPE_BYTE_BINARY : BufferedImage.TYPE_INT_RGB; 44 | return BufferedImage.TYPE_INT_ARGB; 45 | } 46 | 47 | } -------------------------------------------------------------------------------- /src/main/java/com/JUtils/QRCode/MatrixToImageWriter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2009 ZXing authors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.JUtils.QRCode; 18 | 19 | import com.google.zxing.common.BitMatrix; 20 | 21 | import javax.imageio.ImageIO; 22 | import java.io.File; 23 | import java.io.OutputStream; 24 | import java.io.IOException; 25 | import java.awt.image.BufferedImage; 26 | 27 | /** 28 | * Writes a {@link com.google.zxing.common.BitMatrix} to {@link java.awt.image.BufferedImage}, 29 | * file or stream. Provided here instead of core since it depends on 30 | * Java SE libraries. 31 | * 32 | * @author Sean Owen 33 | */ 34 | public final class MatrixToImageWriter { 35 | 36 | private static final MatrixToImageConfig DEFAULT_CONFIG = new MatrixToImageConfig(); 37 | 38 | private MatrixToImageWriter() {} 39 | 40 | /** 41 | * Renders a {@link com.google.zxing.common.BitMatrix} as an image, where "false" bits are rendered 42 | * as white, and "true" bits are rendered as black. 43 | */ 44 | public static BufferedImage toBufferedImage(BitMatrix matrix) { 45 | return toBufferedImage(matrix, DEFAULT_CONFIG); 46 | } 47 | 48 | /** 49 | * As {@link #toBufferedImage(com.google.zxing.common.BitMatrix)}, but allows customization of the output. 50 | */ 51 | public static BufferedImage toBufferedImage(BitMatrix matrix, MatrixToImageConfig config) { 52 | int width = matrix.getWidth(); 53 | int height = matrix.getHeight(); 54 | BufferedImage image = new BufferedImage(width, height, config.getBufferedImageColorModel()); 55 | int onColor = config.getPixelOnColor(); 56 | int offColor = config.getPixelOffColor(); 57 | for (int x = 0; x < width; x++) { 58 | for (int y = 0; y < height; y++) { 59 | image.setRGB(x, y, matrix.get(x, y) ? onColor : offColor); 60 | } 61 | } 62 | return image; 63 | } 64 | 65 | /** 66 | * Writes a {@link com.google.zxing.common.BitMatrix} to a file. 67 | * 68 | * @see #toBufferedImage(com.google.zxing.common.BitMatrix) 69 | */ 70 | public static void writeToFile(BitMatrix matrix, String format, File file) throws IOException { 71 | writeToFile(matrix, format, file, DEFAULT_CONFIG); 72 | } 73 | 74 | /** 75 | * As {@link #writeToFile(com.google.zxing.common.BitMatrix, String, java.io.File)}, but allows customization of the output. 76 | */ 77 | public static void writeToFile(BitMatrix matrix, String format, File file, MatrixToImageConfig config) 78 | throws IOException { 79 | BufferedImage image = toBufferedImage(matrix, config); 80 | if (!ImageIO.write(image, format, file)) { 81 | throw new IOException("Could not write an image of format " + format + " to " + file); 82 | } 83 | } 84 | 85 | /** 86 | * Writes a {@link com.google.zxing.common.BitMatrix} to a stream. 87 | * 88 | * @see #toBufferedImage(com.google.zxing.common.BitMatrix) 89 | */ 90 | public static void writeToStream(BitMatrix matrix, String format, OutputStream stream) throws IOException { 91 | writeToStream(matrix, format, stream, DEFAULT_CONFIG); 92 | } 93 | 94 | /** 95 | * As {@link #writeToStream(com.google.zxing.common.BitMatrix, String, java.io.OutputStream)}, but allows customization of the output. 96 | */ 97 | public static void writeToStream(BitMatrix matrix, String format, OutputStream stream, MatrixToImageConfig config) 98 | throws IOException { 99 | BufferedImage image = toBufferedImage(matrix, config); 100 | if (!ImageIO.write(image, format, stream)) { 101 | throw new IOException("Could not write an image of format " + format); 102 | } 103 | } 104 | 105 | } 106 | -------------------------------------------------------------------------------- /src/main/java/com/JUtils/QRCode/MatrixToImageWriterEx.java: -------------------------------------------------------------------------------- 1 | package com.JUtils.QRCode; 2 | 3 | import java.awt.Graphics2D; 4 | import java.awt.image.BufferedImage; 5 | import java.io.File; 6 | import java.io.IOException; 7 | import java.io.OutputStream; 8 | import java.util.Hashtable; 9 | 10 | import javax.imageio.ImageIO; 11 | 12 | import com.google.zxing.BarcodeFormat; 13 | import com.google.zxing.EncodeHintType; 14 | import com.google.zxing.MultiFormatWriter; 15 | import com.google.zxing.WriterException; 16 | import com.google.zxing.common.BitMatrix; 17 | import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; 18 | 19 | public class MatrixToImageWriterEx { 20 | 21 | 22 | private static final MatrixToLogoImageConfig DEFAULT_CONFIG = new MatrixToLogoImageConfig(); 23 | 24 | /** 25 | * 根据内容生成二维码数据 26 | * @param content 二维码文字内容[为了信息安全性,一般都要先进行数据加密] 27 | * @param width 二维码照片宽度 28 | * @param height 二维码照片高度 29 | * @return 30 | */ 31 | public static BitMatrix createQRCode(String content, int width, int height){ 32 | Hashtable hints = new Hashtable(); 33 | //设置字符编码 34 | hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); 35 | // 指定纠错等级 36 | hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); 37 | hints.put(EncodeHintType.MARGIN, 1); 38 | BitMatrix matrix = null; 39 | try { 40 | matrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints); 41 | } catch (WriterException e) { 42 | e.printStackTrace(); 43 | } 44 | 45 | return matrix; 46 | } 47 | 48 | /** 49 | * 写入二维码、以及将照片logo写入二维码中 50 | * @param matrix 要写入的二维码 51 | * @param format 二维码照片格式 52 | * @param imagePath 二维码照片保存路径 53 | * @param logoPath logo路径 54 | * @throws java.io.IOException 55 | */ 56 | public static void writeToFile(BitMatrix matrix, String format, String imagePath, String logoPath) throws IOException { 57 | MatrixToImageWriter.writeToFile(matrix, format, new File(imagePath), new MatrixToImageConfig()); 58 | 59 | //添加logo图片, 此处一定需要重新进行读取,而不能直接使用二维码的BufferedImage 对象 60 | BufferedImage img = ImageIO.read(new File(imagePath)); 61 | MatrixToImageWriterEx.overlapImage(img, format, imagePath, logoPath, DEFAULT_CONFIG); 62 | } 63 | 64 | /** 65 | * 写入二维码、以及将照片logo写入二维码中 66 | * @param matrix 要写入的二维码 67 | * @param format 二维码照片格式 68 | * @param imagePath 二维码照片保存路径 69 | * @param logoPath logo路径 70 | * @param logoConfig logo配置对象 71 | * @throws java.io.IOException 72 | */ 73 | public static void writeToFile(BitMatrix matrix, String format, String imagePath, String logoPath, MatrixToLogoImageConfig logoConfig) throws IOException { 74 | MatrixToImageWriter.writeToFile(matrix, format, new File(imagePath), new MatrixToImageConfig()); 75 | 76 | //添加logo图片, 此处一定需要重新进行读取,而不能直接使用二维码的BufferedImage 对象 77 | BufferedImage img = ImageIO.read(new File(imagePath)); 78 | MatrixToImageWriterEx.overlapImage(img, format, imagePath, logoPath, logoConfig); 79 | } 80 | 81 | /** 82 | * 将照片logo添加到二维码中间 83 | * @param image 生成的二维码照片对象 84 | * @param imagePath 照片保存路径 85 | * @param logoPath logo照片路径 86 | * @param formate 照片格式 87 | */ 88 | public static void overlapImage(BufferedImage image, String formate, String imagePath, String logoPath, MatrixToLogoImageConfig logoConfig) { 89 | try { 90 | //将logo写入二维码中 91 | drawImage(logoPath, image, logoConfig); 92 | 93 | //写入logo照片到二维码 94 | ImageIO.write(image, formate, new File(imagePath)); 95 | } catch (Exception e) { 96 | e.printStackTrace(); 97 | } 98 | } 99 | 100 | /** 101 | * 将照片添加到二维码中间,并生成流 102 | * @author:chenming 103 | * @date:2014年12月31日 104 | * 105 | * @param matrix 要写入的二维码 106 | * @param formate 照片格式 107 | * @param logoPath 要写入照片的路径 108 | * @param logoConfig logo配置对象 可以为null,为 null 默认 DEFAULT_CONFIG 109 | * @throws java.io.IOException 110 | */ 111 | public static void overlapImage(BitMatrix matrix,String formate,String logoPath,MatrixToLogoImageConfig logoConfig,OutputStream out) throws IOException{ 112 | //将matrix转换为bufferImage 113 | BufferedImage image = MatrixToImageWriter.toBufferedImage(matrix); 114 | 115 | //将logo照片绘制到二维码中间 116 | drawImage(logoPath, image, logoConfig); 117 | 118 | //输出 119 | ImageIO.write(image, formate, out); 120 | } 121 | 122 | /** 123 | * 将照片添加到二维码中间,并生成流 124 | * @author:chenming 125 | * @date:2014年12月31日 126 | * 127 | * @param image 要写入的二维码 128 | * @param formate 照片格式 129 | * @param logoPath 要写入照片的路径 130 | * @param logoConfig logo配置对象 可以为null,为 null 默认 DEFAULT_CONFIG 131 | * @throws java.io.IOException 132 | */ 133 | public static void overlapImage(BufferedImage image,String formate,String logoPath,MatrixToLogoImageConfig logoConfig,OutputStream out) throws IOException{ 134 | //将logo照片绘制到二维码中间 135 | drawImage(logoPath, image, logoConfig); 136 | 137 | //输出 138 | ImageIO.write(image, formate, out); 139 | } 140 | 141 | /** 142 | * 将logo添加到二维码中间 143 | * @author:chenming 144 | * @date:2014年12月31日 145 | * 146 | * @param logoPath logo路径 147 | * @param image 需要绘制的二维码图片 148 | * @param logoConfig 配置参数 149 | * @throws java.io.IOException 150 | */ 151 | private static void drawImage(String logoPath,BufferedImage image,MatrixToLogoImageConfig logoConfig) throws IOException{ 152 | if(logoConfig == null){ 153 | logoConfig = DEFAULT_CONFIG; 154 | } 155 | 156 | try { 157 | BufferedImage logo = ImageIO.read(new File(logoPath)); 158 | logo.setRGB(0, 0, BufferedImage.TYPE_INT_BGR); 159 | Graphics2D g = image.createGraphics(); 160 | 161 | //考虑到logo照片贴到二维码中,建议大小不要超过二维码的1/5; 162 | int width = image.getWidth() / logoConfig.getLogoPart(); 163 | int height = image.getHeight() / logoConfig.getLogoPart(); 164 | 165 | //logo起始位置,此目的是为logo居中显示 166 | int x = (image.getWidth() - width) / 2; 167 | int y = (image.getHeight() - height) / 2; 168 | 169 | //绘制图 170 | g.drawImage(logo, x, y, width, height, null); 171 | 172 | //给logo画边框 173 | //构造一个具有指定线条宽度以及 cap 和 join 风格的默认值的实心 BasicStroke 174 | // g.setStroke(new BasicStroke(logoConfig.getBorder())); 175 | // g.setColor(logoConfig.getBorderColor()); 176 | // g.drawRect(x, y, width, height); 177 | 178 | g.dispose(); 179 | } catch (Exception e) { //捕捉异常后不做任何处理,防止图片路径错误而导致二维码生成失败 180 | 181 | } 182 | } 183 | 184 | } 185 | -------------------------------------------------------------------------------- /src/main/java/com/JUtils/QRCode/MatrixToLogoImageConfig.java: -------------------------------------------------------------------------------- 1 | package com.JUtils.QRCode; 2 | 3 | import java.awt.Color; 4 | 5 | public class MatrixToLogoImageConfig { 6 | //logo默认边框颜色 7 | public static final Color DEFAULT_BORDERCOLOR = Color.RED; 8 | //logo默认边框宽度 9 | public static final int DEFAULT_BORDER = 2; 10 | //logo大小默认为照片的1/5 11 | public static final int DEFAULT_LOGOPART = 5; 12 | 13 | private final int border = DEFAULT_BORDER; 14 | private final Color borderColor; 15 | private final int logoPart; 16 | 17 | /** 18 | * Creates a default config with on color {@link #BLACK} and off color 19 | * {@link #WHITE}, generating normal black-on-white barcodes. 20 | */ 21 | public MatrixToLogoImageConfig() { 22 | this(DEFAULT_BORDERCOLOR, DEFAULT_LOGOPART); 23 | } 24 | 25 | 26 | public MatrixToLogoImageConfig(Color borderColor, int logoPart) { 27 | this.borderColor = borderColor; 28 | this.logoPart = logoPart; 29 | } 30 | 31 | 32 | public Color getBorderColor() { 33 | return borderColor; 34 | } 35 | 36 | 37 | public int getBorder() { 38 | return border; 39 | } 40 | 41 | 42 | public int getLogoPart() { 43 | return logoPart; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/JUtils/base/ConvertUtils.java: -------------------------------------------------------------------------------- 1 | package com.JUtils.base; 2 | 3 | import java.sql.Timestamp; 4 | import java.text.SimpleDateFormat; 5 | 6 | /** 7 | * 转换工具类
8 | * 若待转换值为null或者出现异常,则使用默认值 9 | * 10 | * @Author:chenssy 11 | * @date:2016年5月21日 上午10:18:12 12 | */ 13 | public class ConvertUtils { 14 | 15 | /** 16 | * 字符串转换为int 17 | * 18 | * @author:chenssy 19 | * @date : 2016年5月21日 上午10:16:27 20 | * 21 | * @param str 22 | * 待转换的字符串 23 | * @param defaultValue 24 | * 默认值 25 | * @return 26 | */ 27 | public static int strToInt(String str, int defaultValue) { 28 | try { 29 | defaultValue = Integer.parseInt(str); 30 | } catch (Exception localException) { 31 | } 32 | return defaultValue; 33 | } 34 | 35 | /** 36 | * String转换为long 37 | * 38 | * @author:chenssy 39 | * @date : 2016年5月21日 上午10:18:44 40 | * 41 | * @param str 42 | * 待转换字符串 43 | * @param defaultValue 44 | * 默认值 45 | * @return 46 | */ 47 | public static long strToLong(String str, long defaultValue) { 48 | try { 49 | defaultValue = Long.parseLong(str); 50 | } catch (Exception localException) { 51 | } 52 | return defaultValue; 53 | } 54 | 55 | /** 56 | * 字符串转换为float 57 | * 58 | * @author:chenssy 59 | * @date : 2016年5月21日 上午10:19:12 60 | * 61 | * @param str 62 | * 63 | * @param defaultValue 64 | * @return 65 | */ 66 | public static float strToFloat(String str, float defaultValue) { 67 | try { 68 | defaultValue = Float.parseFloat(str); 69 | } catch (Exception localException) { 70 | } 71 | return defaultValue; 72 | } 73 | 74 | /** 75 | * String转换为Double 76 | * 77 | * @author:chenssy 78 | * @date : 2016年5月21日 上午10:21:59 79 | * 80 | * @param str 81 | * 待转换字符串 82 | * @param defaultValue 83 | * 默认值 84 | * @return 85 | */ 86 | public static double strToDouble(String str, double defaultValue) { 87 | try { 88 | defaultValue = Double.parseDouble(str); 89 | } catch (Exception localException) { 90 | } 91 | return defaultValue; 92 | } 93 | 94 | /** 95 | * 字符串转换日期 96 | * 97 | * @author:chenssy 98 | * @date : 2016年5月21日 上午10:27:01 99 | * 100 | * @param str 101 | * 待转换的字符串 102 | * @param defaultValue 103 | * 默认日期 104 | * @return 105 | */ 106 | public static java.util.Date strToDate(String str,java.util.Date defaultValue) { 107 | return strToDate(str, "yyyy-MM-dd HH:mm:ss", defaultValue); 108 | } 109 | 110 | /** 111 | * 字符串转换为指定格式的日期 112 | * 113 | * @author:chenssy 114 | * @date : 2016年5月21日 上午10:27:24 115 | * 116 | * @param str 117 | * 待转换的字符串 118 | * @param format 119 | * 日期格式 120 | * @param defaultValue 121 | * 默认日期 122 | * @return 123 | */ 124 | public static java.util.Date strToDate(String str, String format,java.util.Date defaultValue) { 125 | SimpleDateFormat fmt = new SimpleDateFormat(format); 126 | try { 127 | defaultValue = fmt.parse(str); 128 | } catch (Exception localException) { 129 | } 130 | return defaultValue; 131 | } 132 | 133 | /** 134 | * 日期转换为字符串 135 | * 136 | * @author:chenssy 137 | * @date : 2016年5月21日 上午10:28:05 138 | * 139 | * @param date 140 | * 待转换的日期 141 | * @param defaultValue 142 | * 默认字符串 143 | * @return 144 | */ 145 | public static String dateToStr(java.util.Date date, String defaultValue) { 146 | return dateToStr(date, "yyyy-MM-dd HH:mm:ss", defaultValue); 147 | } 148 | 149 | /** 150 | * 日期转换为指定格式的字符串 151 | * 152 | * @author:chenssy 153 | * @date : 2016年5月21日 上午10:28:51 154 | * 155 | * @param date 156 | * 待转换的日期 157 | * @param format 158 | * 指定格式 159 | * @param defaultValue 160 | * 默认值 161 | * @return 162 | */ 163 | public static String dateToStr(java.util.Date date, String format, String defaultValue) { 164 | SimpleDateFormat sdf = new SimpleDateFormat(format); 165 | try { 166 | defaultValue = sdf.format(date); 167 | } catch (Exception localException) { 168 | } 169 | return defaultValue; 170 | } 171 | 172 | /** 173 | * 如果字符串为空则使用默认字符串 174 | * 175 | * @author:chenssy 176 | * @date : 2016年5月21日 上午10:29:35 177 | * 178 | * @param str 179 | * 字符串 180 | * @param defaultValue 181 | * 默认值 182 | * @return 183 | */ 184 | public static String strToStr(String str, String defaultValue) { 185 | if ((str != null) && (!(str.isEmpty()))) 186 | defaultValue = str; 187 | return defaultValue; 188 | } 189 | 190 | /** 191 | * util date 转换为 sqldate 192 | * 193 | * @author:chenssy 194 | * @date : 2016年5月21日 上午10:30:09 195 | * 196 | * @param date 197 | * @return 198 | */ 199 | public static java.sql.Date dateToSqlDate(java.util.Date date) { 200 | return new java.sql.Date(date.getTime()); 201 | } 202 | 203 | /** 204 | * sql date 转换为 util date 205 | * 206 | * @author:chenssy 207 | * @date : 2016年5月21日 上午10:30:26 208 | * 209 | * @param date 210 | * @return 211 | */ 212 | public static java.util.Date sqlDateToDate(java.sql.Date date) { 213 | return new java.util.Date(date.getTime()); 214 | } 215 | 216 | /** 217 | * date 转换为 timestamp 218 | * 219 | * @author:chenssy 220 | * @date : 2016年5月21日 上午10:30:51 221 | * 222 | * @param date 223 | * @return 224 | */ 225 | public static Timestamp dateToSqlTimestamp(java.util.Date date) { 226 | return new Timestamp(date.getTime()); 227 | } 228 | 229 | /** 230 | * timestamp 转换为date 231 | * 232 | * @author:chenssy 233 | * @date : 2016年5月21日 上午10:31:13 234 | * 235 | * @param date 236 | * @return 237 | */ 238 | public static java.util.Date qlTimestampToDate(Timestamp date) { 239 | return new java.util.Date(date.getTime()); 240 | } 241 | } 242 | -------------------------------------------------------------------------------- /src/main/java/com/JUtils/base/IdcardValidator.java: -------------------------------------------------------------------------------- 1 | package com.JUtils.base; 2 | 3 | import java.util.regex.Pattern; 4 | 5 | /** 6 | * --15位身份证号码:第7、8位为出生年份(两位数),第9、10位为出生月份,第11、12位代表出生日期,第15位代表性别,奇数为男,偶数为女。 7 | * --18位身份证号码 8 | * :第7、8、9、10位为出生年份(四位数),第11、第12位为出生月份,第13、14位代表出生日期,第17位代表性别,奇数为男,偶数为女。 9 | * 10 | * @Author:chenssy 11 | * @date:2016年6月1日 下午12:29:41 12 | * 13 | */ 14 | public class IdcardValidator { 15 | 16 | /** 17 | * 省,直辖市代码表: { 11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古", 18 | * 21:"辽宁",22:"吉林",23:"黑龙江",31:"上海",32:"江苏", 19 | * 33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南", 20 | * 42:"湖北",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆", 21 | * 51:"四川",52:"贵州",53:"云南",54:"西藏",61:"陕西",62:"甘肃", 22 | * 63:"青海",64:"宁夏",65:"新疆",71:"台湾",81:"香港",82:"澳门",91:"国外"} 23 | */ 24 | 25 | // 每位加权因子 26 | private static int power[] = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 }; 27 | 28 | /** 29 | * 验证身份证是否合法 30 | * 31 | * @author : chenssy 32 | * @date : 2016年6月1日 下午12:30:03 33 | * 34 | * @param idcard 35 | * @return 36 | */ 37 | @SuppressWarnings("static-access") 38 | public boolean isValidatedAllIdcard(String idcard) { 39 | return this.isValidate18Idcard(idcard); 40 | } 41 | 42 | /** 43 | * 44 |

45 | * 判断18位身份证的合法性 46 | *

47 | * 根据〖中华人民共和国国家标准GB11643-1999〗中有关公民身份号码的规定,公民身份号码是特征组合码,由十七位数字本体码和一位数字校验码组成。 48 | * 排列顺序从左至右依次为:六位数字地址码,八位数字出生日期码,三位数字顺序码和一位数字校验码。 49 | *

50 | * 顺序码: 表示在同一地址码所标识的区域范围内,对同年、同月、同 日出生的人编定的顺序号,顺序码的奇数分配给男性,偶数分配 给女性。 51 | *

52 | *

53 | * 1.前1、2位数字表示:所在省份的代码; 2.第3、4位数字表示:所在城市的代码; 3.第5、6位数字表示:所在区县的代码; 54 | * 4.第7~14位数字表示:出生年、月、日; 5.第15、16位数字表示:所在地的派出所的代码; 55 | * 6.第17位数字表示性别:奇数表示男性,偶数表示女性; 56 | * 7.第18位数字是校检码:也有的说是个人信息码,一般是随计算机的随机产生,用来检验身份证的正确性。校检码可以是0~9的数字,有时也用x表示。 57 | *

58 | *

59 | * 第十八位数字(校验码)的计算方法为: 1.将前面的身份证号码17位数分别乘以不同的系数。从第一位到第十七位的系数分别为:7 9 10 5 8 4 60 | * 2 1 6 3 7 9 10 5 8 4 2 61 | *

62 | *

63 | * 2.将这17位数字和系数相乘的结果相加。 64 | *

65 | *

66 | * 3.用加出来和除以11,看余数是多少? 67 | *

68 | * 4.余数只可能有0 1 2 3 4 5 6 7 8 9 10这11个数字。其分别对应的最后一位身份证的号码为1 0 X 9 8 7 6 5 4 3 69 | * 2。 70 | *

71 | * 5.通过上面得知如果余数是2,就会在身份证的第18位数字上出现罗马数字的Ⅹ。如果余数是10,身份证的最后一位号码就是2。 72 | *

73 | * 74 | * @author : chenssy 75 | * @date : 2016年6月1日 下午12:31:10 76 | * 77 | * @param idcard 78 | * 待验证的身份证 79 | * @return 80 | */ 81 | public static boolean isValidate18Idcard(String idcard) { 82 | // 非18位为假 83 | if (idcard.length() != 18) { 84 | return false; 85 | } 86 | // 获取前17位 87 | String idcard17 = idcard.substring(0, 17); 88 | // 获取第18位 89 | String idcard18Code = idcard.substring(17, 18); 90 | char c[] = null; 91 | String checkCode = ""; 92 | // 是否都为数字 93 | if (isDigital(idcard17)) { 94 | c = idcard17.toCharArray(); 95 | } else { 96 | return false; 97 | } 98 | 99 | if (null != c) { 100 | int bit[] = new int[idcard17.length()]; 101 | bit = converCharToInt(c); 102 | int sum17 = 0; 103 | sum17 = getPowerSum(bit); 104 | // 将和值与11取模得到余数进行校验码判断 105 | checkCode = getCheckCodeBySum(sum17); 106 | if (null == checkCode) { 107 | return false; 108 | } 109 | // 将身份证的第18位与算出来的校码进行匹配,不相等就为假 110 | if (!idcard18Code.equalsIgnoreCase(checkCode)) { 111 | return false; 112 | } 113 | } 114 | 115 | return true; 116 | } 117 | 118 | /** 119 | * 18位身份证号码的基本数字和位数验校 120 | * 121 | * @author : chenssy 122 | * @date : 2016年6月1日 下午12:31:49 123 | * 124 | * @param idcard 125 | * 待验证的身份证 126 | * @return 127 | */ 128 | public static boolean is18Idcard(String idcard) { 129 | return Pattern.matches("^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([\\d|x|X]{1})$", idcard); 130 | } 131 | 132 | /** 133 | * 数字验证 134 | * 135 | * @author : chenssy 136 | * @date : 2016年6月1日 下午12:32:18 137 | * 138 | * @param str 139 | * @return 140 | */ 141 | private static boolean isDigital(String str) { 142 | return str == null || "".equals(str) ? false : str.matches("^[0-9]*$"); 143 | } 144 | 145 | /** 146 | * 将身份证的每位和对应位的加权因子相乘之后,再得到和值 147 | * 148 | * @author : chenssy 149 | * @date : 2016年6月1日 下午12:32:34 150 | * 151 | * @param bit 152 | * @return 153 | */ 154 | private static int getPowerSum(int[] bit) { 155 | int sum = 0; 156 | if (power.length != bit.length) { 157 | return sum; 158 | } 159 | 160 | for (int i = 0; i < bit.length; i++) { 161 | for (int j = 0; j < power.length; j++) { 162 | if (i == j) { 163 | sum = sum + bit[i] * power[j]; 164 | } 165 | } 166 | } 167 | 168 | return sum; 169 | } 170 | 171 | /** 172 | * 将和值与11取模得到余数进行校验码判断 173 | * 174 | * @author : chenssy 175 | * @date : 2016年6月1日 下午12:32:51 176 | * 177 | * @param sum17 178 | * @return 179 | */ 180 | private static String getCheckCodeBySum(int sum17) { 181 | String checkCode = null; 182 | switch (sum17 % 11) { 183 | case 10: 184 | checkCode = "2"; 185 | break; 186 | case 9: 187 | checkCode = "3"; 188 | break; 189 | case 8: 190 | checkCode = "4"; 191 | break; 192 | case 7: 193 | checkCode = "5"; 194 | break; 195 | case 6: 196 | checkCode = "6"; 197 | break; 198 | case 5: 199 | checkCode = "7"; 200 | break; 201 | case 4: 202 | checkCode = "8"; 203 | break; 204 | case 3: 205 | checkCode = "9"; 206 | break; 207 | case 2: 208 | checkCode = "x"; 209 | break; 210 | case 1: 211 | checkCode = "0"; 212 | break; 213 | case 0: 214 | checkCode = "1"; 215 | break; 216 | } 217 | return checkCode; 218 | } 219 | 220 | /** 221 | * 将字符数组转为整型数组 222 | * 223 | * @author : chenssy 224 | * @date : 2016年6月1日 下午12:33:22 225 | * 226 | * @param c 227 | * @return 228 | * @throws NumberFormatException 229 | */ 230 | private static int[] converCharToInt(char[] c) throws NumberFormatException { 231 | int[] a = new int[c.length]; 232 | int k = 0; 233 | for (char temp : c) { 234 | a[k++] = Integer.parseInt(String.valueOf(temp)); 235 | } 236 | return a; 237 | } 238 | 239 | /** 240 | * 241 | * @param idno 242 | * @return 身份证信息中代表性别的数值 243 | */ 244 | public static int getUserSex(String idno) { 245 | String sex="1"; 246 | if(idno!=null){ 247 | if(idno.length()>15){ 248 | sex = idno.substring(16, 17); 249 | } 250 | } 251 | 252 | return Integer.parseInt(sex) % 2==0 ? 0:1; 253 | } 254 | } 255 | -------------------------------------------------------------------------------- /src/main/java/com/JUtils/base/MoneyUtils.java: -------------------------------------------------------------------------------- 1 | package com.JUtils.base; 2 | 3 | import java.math.BigDecimal; 4 | import java.math.RoundingMode; 5 | 6 | /** 7 | * 金钱处理工具类 8 | * 9 | * @Author:chenssy 10 | * @date:2014年8月7日 11 | */ 12 | public class MoneyUtils { 13 | 14 | /** 15 | * 汉语中数字大写 16 | */ 17 | private static final String[] CN_UPPER_NUMBER = {"零","壹","贰","叁","肆","伍","陆","柒","捌","玖" }; 18 | 19 | /** 20 | * 汉语中货币单位大写 21 | */ 22 | private static final String[] CN_UPPER_MONETRAY_UNIT = { "分", "角", "元","拾", "佰", "仟", "万", "拾", 23 | "佰", "仟", "亿", "拾", "佰", "仟", "兆", "拾", 24 | "佰", "仟" }; 25 | /** 26 | * 特殊字符:整 27 | */ 28 | private static final String CN_FULL = ""; 29 | 30 | /** 31 | * 特殊字符:负 32 | */ 33 | private static final String CN_NEGATIVE = "负"; 34 | /** 35 | * 零元整 36 | */ 37 | private static final String CN_ZEOR_FULL = "零元整"; 38 | 39 | /** 40 | * 金额的精度,默认值为2 41 | */ 42 | private static final int MONEY_PRECISION = 2; 43 | 44 | /** 45 | * 人民币转换为大写,格式为:x万x千x百x十x元x角x分 46 | * 47 | * @autor:chenssy 48 | * @date:2014年8月7日 49 | * 50 | * @param numberOfMoney 传入的金额 51 | * @return 52 | */ 53 | public static String number2CNMontray(String numberOfMoney) { 54 | return number2CNMontray(new BigDecimal(numberOfMoney)); 55 | } 56 | 57 | 58 | /** 59 | * 人民币转换为大写,格式为:x万x千x百x十x元x角x分 60 | * @autor:chenssy 61 | * @date:2014年8月7日 62 | * 63 | * @param numberOfMoney 64 | * 传入的金额 65 | * @return 66 | */ 67 | public static String number2CNMontray(BigDecimal numberOfMoney) { 68 | StringBuffer sb = new StringBuffer(); 69 | int signum = numberOfMoney.signum(); 70 | // 零元整的情况 71 | if (signum == 0) { 72 | return CN_ZEOR_FULL; 73 | } 74 | //这里会进行金额的四舍五入 75 | long number = numberOfMoney.movePointRight(MONEY_PRECISION).setScale(0, 4).abs().longValue(); 76 | // 得到小数点后两位值 77 | long scale = number % 100; 78 | int numUnit = 0; 79 | int numIndex = 0; 80 | boolean getZero = false; 81 | // 判断最后两位数,一共有四中情况:00 = 0, 01 = 1, 10, 11 82 | if (!(scale > 0)) { 83 | numIndex = 2; 84 | number = number / 100; 85 | getZero = true; 86 | } 87 | if ((scale > 0) && (!(scale % 10 > 0))) { 88 | numIndex = 1; 89 | number = number / 10; 90 | getZero = true; 91 | } 92 | int zeroSize = 0; 93 | while (true) { 94 | if (number <= 0) { 95 | break; 96 | } 97 | // 每次获取到最后一个数 98 | numUnit = (int) (number % 10); 99 | if (numUnit > 0) { 100 | if ((numIndex == 9) && (zeroSize >= 3)) { 101 | sb.insert(0, CN_UPPER_MONETRAY_UNIT[6]); 102 | } 103 | if ((numIndex == 13) && (zeroSize >= 3)) { 104 | sb.insert(0, CN_UPPER_MONETRAY_UNIT[10]); 105 | } 106 | sb.insert(0, CN_UPPER_MONETRAY_UNIT[numIndex]); 107 | sb.insert(0, CN_UPPER_NUMBER[numUnit]); 108 | getZero = false; 109 | zeroSize = 0; 110 | } else { 111 | ++zeroSize; 112 | if (!(getZero)) { 113 | sb.insert(0, CN_UPPER_NUMBER[numUnit]); 114 | } 115 | if (numIndex == 2) { 116 | if (number > 0) { 117 | sb.insert(0, CN_UPPER_MONETRAY_UNIT[numIndex]); 118 | } 119 | } else if (((numIndex - 2) % 4 == 0) && (number % 1000 > 0)) { 120 | sb.insert(0, CN_UPPER_MONETRAY_UNIT[numIndex]); 121 | } 122 | getZero = true; 123 | } 124 | // 让number每次都去掉最后一个数 125 | number = number / 10; 126 | ++numIndex; 127 | } 128 | // 如果signum == -1,则说明输入的数字为负数,就在最前面追加特殊字符:负 129 | if (signum == -1) { 130 | sb.insert(0, CN_NEGATIVE); 131 | } 132 | // 输入的数字小数点后两位为"00"的情况,则要在最后追加特殊字符:整 133 | if (!(scale > 0)) { 134 | sb.append(CN_FULL); 135 | } 136 | return sb.toString(); 137 | } 138 | 139 | /** 140 | * 将人民币转换为会计格式金额(xxxx,xxxx,xxxx.xx),保留两位小数 141 | * @autor:chenssy 142 | * @date:2014年8月7日 143 | * 144 | * @param money 145 | * 待转换的金额 146 | * @return 147 | */ 148 | public static String accountantMoney(BigDecimal money){ 149 | return accountantMoney(money, 2, 1); 150 | } 151 | 152 | /** 153 | * 格式化金额,显示为xxx万元,xxx百万,xxx亿 154 | * @autor:chenssy 155 | * @date:2014年8月7日 156 | * 157 | * @param money 158 | * 待处理的金额 159 | * @param scale 160 | * 小数点后保留的位数 161 | * @param divisor 162 | * 格式化值(10:十元、100:百元,1000千元,10000万元......) 163 | * @return 164 | */ 165 | public static String getFormatMoney(BigDecimal money,int scale,double divisor){ 166 | return formatMoney(money, scale, divisor) + getCellFormat(divisor); 167 | } 168 | 169 | /** 170 | * 获取会计格式的人民币(格式为:xxxx,xxxx,xxxx.xx) 171 | * @autor:chenssy 172 | * @date:2014年8月7日 173 | * 174 | * @param money 175 | * 待处理的金额 176 | * @param scale 177 | * 小数点后保留的位数 178 | * @param divisor 179 | * 格式化值(10:十元、100:百元,1000千元,10000万元......) 180 | * @return 181 | */ 182 | public static String getAccountantMoney(BigDecimal money, int scale, double divisor){ 183 | return accountantMoney(money, scale, divisor) + getCellFormat(divisor); 184 | } 185 | 186 | /** 187 | * 将人民币转换为会计格式金额(xxxx,xxxx,xxxx.xx) 188 | * @autor:chenssy 189 | * @date:2014年8月7日 190 | * 191 | * @param money 192 | * 待处理的金额 193 | * @param scale 194 | * 小数点后保留的位数 195 | * @param divisor 196 | * 格式化值 197 | * @return 198 | */ 199 | private static String accountantMoney(BigDecimal money,int scale,double divisor){ 200 | String disposeMoneyStr = formatMoney(money, scale, divisor); 201 | //小数点处理 202 | int dotPosition = disposeMoneyStr.indexOf("."); 203 | String exceptDotMoeny = null;//小数点之前的字符串 204 | String dotMeony = null;//小数点之后的字符串 205 | if(dotPosition > 0){ 206 | exceptDotMoeny = disposeMoneyStr.substring(0,dotPosition); 207 | dotMeony = disposeMoneyStr.substring(dotPosition); 208 | }else{ 209 | exceptDotMoeny = disposeMoneyStr; 210 | } 211 | //负数处理 212 | int negativePosition = exceptDotMoeny.indexOf("-"); 213 | if(negativePosition == 0){ 214 | exceptDotMoeny = exceptDotMoeny.substring(1); 215 | } 216 | StringBuffer reverseExceptDotMoney = new StringBuffer(exceptDotMoeny); 217 | reverseExceptDotMoney.reverse();//字符串倒转 218 | char[] moneyChar = reverseExceptDotMoney.toString().toCharArray(); 219 | StringBuffer returnMeony = new StringBuffer();//返回值 220 | for(int i = 0; i < moneyChar.length; i++){ 221 | if(i != 0 && i % 3 == 0){ 222 | returnMeony.append(",");//每隔3位加',' 223 | } 224 | returnMeony.append(moneyChar[i]); 225 | } 226 | returnMeony.reverse();//字符串倒转 227 | if(dotPosition > 0){ 228 | returnMeony.append(dotMeony); 229 | } 230 | if(negativePosition == 0){ 231 | return "-" + returnMeony.toString(); 232 | }else{ 233 | return returnMeony.toString(); 234 | } 235 | } 236 | 237 | /** 238 | * 格式化金额,显示为xxx万元,xxx百万,xxx亿 239 | * @autor:chenssy 240 | * @date:2014年8月7日 241 | * 242 | * @param money 243 | * 待处理的金额 244 | * @param scale 245 | * 小数点后保留的位数 246 | * @param divisor 247 | * 格式化值 248 | * @return 249 | */ 250 | private static String formatMoney(BigDecimal money,int scale,double divisor){ 251 | if (divisor == 0) { 252 | return "0.00"; 253 | } 254 | if (scale < 0) { 255 | return "0.00"; 256 | } 257 | BigDecimal divisorBD = new BigDecimal(divisor); 258 | return money.divide(divisorBD, scale, RoundingMode.HALF_UP).toString(); 259 | } 260 | 261 | private static String getCellFormat(double divisor){ 262 | String str = String.valueOf(divisor); 263 | int len = str.substring(0,str.indexOf(".")).length(); 264 | String cell = ""; 265 | switch(len){ 266 | case 1: 267 | cell = "元"; 268 | break; 269 | case 2: 270 | cell = "十元"; 271 | break; 272 | case 3: 273 | cell = "百元"; 274 | break; 275 | case 4: 276 | cell = "千元"; 277 | break; 278 | case 5: 279 | cell = "万元"; 280 | break; 281 | case 6: 282 | cell = "十万元"; 283 | break; 284 | case 7: 285 | cell = "百万元"; 286 | break; 287 | case 8: 288 | cell = "千万元"; 289 | break; 290 | case 9: 291 | cell = "亿元"; 292 | break; 293 | case 10: 294 | cell = "十亿元"; 295 | break; 296 | } 297 | return cell; 298 | } 299 | } 300 | -------------------------------------------------------------------------------- /src/main/java/com/JUtils/base/RegexUtils.java: -------------------------------------------------------------------------------- 1 | package com.JUtils.base; 2 | 3 | import java.util.regex.Matcher; 4 | import java.util.regex.Pattern; 5 | 6 | /** 7 | * 正则表达式工具类,验证数据是否符合规范 8 | * 9 | * @Author:chenssy 10 | * @date:2014年8月7日 11 | */ 12 | public class RegexUtils { 13 | 14 | /** 15 | * 判断字符串是否符合正则表达式 16 | * 17 | * @author : chenssy 18 | * @date : 2016年6月1日 下午12:43:05 19 | * 20 | * @param str 21 | * @param regex 22 | * @return 23 | */ 24 | public static boolean find(String str, String regex) { 25 | Pattern p = Pattern.compile(regex); 26 | Matcher m = p.matcher(str); 27 | boolean b = m.find(); 28 | return b; 29 | } 30 | 31 | /** 32 | * 判断输入的字符串是否符合Email格式. 33 | * @autor:chenssy 34 | * @date:2014年8月7日 35 | * 36 | * @param email 37 | * 传入的字符串 38 | * @return 符合Email格式返回true,否则返回false 39 | */ 40 | public static boolean isEmail(String email) { 41 | if (email == null || email.length() < 1 || email.length() > 256) { 42 | return false; 43 | } 44 | Pattern pattern = Pattern.compile("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$"); 45 | return pattern.matcher(email).matches(); 46 | } 47 | 48 | /** 49 | * 判断输入的字符串是否为纯汉字 50 | * @autor:chenssy 51 | * @date:2014年8月7日 52 | * 53 | * @param value 54 | * 传入的字符串 55 | * @return 56 | */ 57 | public static boolean isChinese(String value) { 58 | Pattern pattern = Pattern.compile("[\u0391-\uFFE5]+$"); 59 | return pattern.matcher(value).matches(); 60 | } 61 | 62 | /** 63 | * 判断是否为浮点数,包括double和float 64 | * @autor:chenssy 65 | * @date:2014年8月7日 66 | * 67 | * @param value 68 | * 传入的字符串 69 | * @return 70 | */ 71 | public static boolean isDouble(String value) { 72 | Pattern pattern = Pattern.compile("^[-\\+]?\\d+\\.\\d+$"); 73 | return pattern.matcher(value).matches(); 74 | } 75 | 76 | /** 77 | * 判断是否为整数 78 | * @autor:chenssy 79 | * @date:2014年8月7日 80 | * 81 | * @param value 82 | * 传入的字符串 83 | * @return 84 | */ 85 | public static boolean isInteger(String value) { 86 | Pattern pattern = Pattern.compile("^[-\\+]?[\\d]+$"); 87 | return pattern.matcher(value).matches(); 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /src/main/java/com/JUtils/base/StringUtils.java: -------------------------------------------------------------------------------- 1 | package com.JUtils.base; 2 | 3 | import java.util.regex.Matcher; 4 | import java.util.regex.Pattern; 5 | 6 | /** 7 | * 8 | * 字符串工具类,对字符串进行常规的处理 9 | * 10 | * @Author:chenssy 11 | * @date:2014年8月5日 12 | */ 13 | public class StringUtils { 14 | 15 | /** 16 | * 将半角的符号转换成全角符号.(即英文字符转中文字符) 17 | * @autor:chenssy 18 | * @date:2014年8月7日 19 | * 20 | * @param str 21 | * 要转换的字符 22 | * @return 23 | */ 24 | public static String changeToFull(String str) { 25 | String source = "1234567890!@#$%^&*()abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_=+\\|[];:'\",<.>/?"; 26 | String[] decode = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", 27 | "!", "@", "#", "$", "%", "︿", "&", "*", "(", ")", "a", "b", 28 | "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", 29 | "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", 30 | "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", 31 | "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", 32 | "Y", "Z", "-", "_", "=", "+", "\", "|", "【", "】", ";", ":", 33 | "'", "\"", ",", "〈", "。", "〉", "/", "?" }; 34 | String result = ""; 35 | for (int i = 0; i < str.length(); i++) { 36 | int pos = source.indexOf(str.charAt(i)); 37 | if (pos != -1) { 38 | result += decode[pos]; 39 | } else { 40 | result += str.charAt(i); 41 | } 42 | } 43 | return result; 44 | } 45 | 46 | /** 47 | * 将字符转换为编码为Unicode,格式 为'\u0020'
48 | * unicodeEscaped(' ') = "\u0020"
49 | * unicodeEscaped('A') = "\u0041" 50 | * @autor:chenssy 51 | * @date:2014年8月7日 52 | * 53 | * @param ch 54 | * 待转换的char 字符 55 | * @return 56 | */ 57 | public static String unicodeEscaped(char ch) { 58 | if (ch < 0x10) { 59 | return "\\u000" + Integer.toHexString(ch); 60 | } else if (ch < 0x100) { 61 | return "\\u00" + Integer.toHexString(ch); 62 | } else if (ch < 0x1000) { 63 | return "\\u0" + Integer.toHexString(ch); 64 | } 65 | return "\\u" + Integer.toHexString(ch); 66 | } 67 | 68 | /** 69 | * 进行toString操作,若为空,返回默认值 70 | * @autor:chenssy 71 | * @date:2014年8月9日 72 | * 73 | * @param object 74 | * 要进行toString操作的对象 75 | * @param nullStr 76 | * 返回的默认值 77 | * @return 78 | */ 79 | public static String toString(Object object,String nullStr){ 80 | return object == null ? nullStr : object.toString(); 81 | } 82 | 83 | /** 84 | * 将字符串重复N次,null、""不在循环次数里面
85 | * 当value == null || value == "" return value;
86 | * 当count <= 1 返回 value 87 | * @autor:chenssy 88 | * @date:2014年8月9日 89 | * 90 | * @param value 91 | * 需要循环的字符串 92 | * @param count 93 | * 循环的次数 94 | * @return 95 | */ 96 | public static String repeatString(String value,int count){ 97 | if(value == null || "".equals(value) || count <= 1){ 98 | return value; 99 | } 100 | 101 | int length = value.length(); 102 | if(length == 1){ //长度为1,存在字符 103 | return repeatChar(value.charAt(0), count); 104 | } 105 | 106 | int outputLength = length * count; 107 | switch (length) { 108 | case 1: 109 | return repeatChar(value.charAt(0), count); 110 | case 2: 111 | char ch0 = value.charAt(0); 112 | char ch1 = value.charAt(1); 113 | char[] output2 = new char[outputLength]; 114 | for (int i = count * 2 - 2; i >= 0; i--, i--) { 115 | output2[i] = ch0; 116 | output2[i + 1] = ch1; 117 | } 118 | return new String(output2); 119 | default: 120 | StringBuilder buf = new StringBuilder(outputLength); 121 | for (int i = 0; i < count; i++) { 122 | buf.append(value); 123 | } 124 | return buf.toString(); 125 | } 126 | 127 | } 128 | 129 | /** 130 | * 将某个字符重复N次 131 | * @autor:chenssy 132 | * @date:2014年8月9日 133 | * 134 | * @param ch 135 | * 需要循环的字符 136 | * @param count 137 | * 循环的次数 138 | * @return 139 | */ 140 | public static String repeatChar(char ch, int count) { 141 | char[] buf = new char[count]; 142 | for (int i = count - 1; i >= 0; i--) { 143 | buf[i] = ch; 144 | } 145 | return new String(buf); 146 | } 147 | 148 | /** 149 | * 判断字符串是否全部都为小写 150 | * @autor:chenssy 151 | * @date:2014年8月9日 152 | * 153 | * @param value 154 | * 待判断的字符串 155 | * @return 156 | */ 157 | public static boolean isAllLowerCase(String value){ 158 | if(value == null || "".equals(value)){ 159 | return false; 160 | } 161 | for (int i = 0; i < value.length(); i++) { 162 | if (Character.isLowerCase(value.charAt(i)) == false) { 163 | return false; 164 | } 165 | } 166 | return true; 167 | } 168 | 169 | /** 170 | * 判断字符串是否全部大写 171 | * @autor:chenssy 172 | * @date:2014年8月9日 173 | * 174 | * @param value 175 | * 待判断的字符串 176 | * @return 177 | */ 178 | public static boolean isAllUpperCase(String value){ 179 | if(value == null || "".equals(value)){ 180 | return false; 181 | } 182 | for (int i = 0; i < value.length(); i++) { 183 | if (Character.isUpperCase(value.charAt(i)) == false) { 184 | return false; 185 | } 186 | } 187 | return true; 188 | } 189 | 190 | /** 191 | * 反转字符串 192 | * @autor:chenssy 193 | * @date:2014年8月9日 194 | * 195 | * @param value 196 | * 待反转的字符串 197 | * @return 198 | */ 199 | public static String reverse(String value){ 200 | if(value == null){ 201 | return null; 202 | } 203 | return new StringBuffer(value).reverse().toString(); 204 | } 205 | 206 | /** 207 | * @desc:截取字符串,支持中英文混乱,其中中文当做两位处理 208 | * @autor:chenssy 209 | * @date:2014年8月10日 210 | * 211 | * @param resourceString 212 | * @param length 213 | * @return 214 | */ 215 | public static String subString(String resourceString,int length){ 216 | String resultString = ""; 217 | if (resourceString == null || "".equals(resourceString) || length < 1) { 218 | return resourceString; 219 | } 220 | 221 | if (resourceString.length() < length) { 222 | return resourceString; 223 | } 224 | 225 | char[] chr = resourceString.toCharArray(); 226 | int strNum = 0; 227 | int strGBKNum = 0; 228 | boolean isHaveDot = false; 229 | 230 | for (int i = 0; i < resourceString.length(); i++) { 231 | if (chr[i] >= 0xa1){// 0xa1汉字最小位开始 232 | strNum = strNum + 2; 233 | strGBKNum++; 234 | } else { 235 | strNum++; 236 | } 237 | 238 | if (strNum == length || strNum == length + 1) { 239 | if (i + 1 < resourceString.length()) { 240 | isHaveDot = true; 241 | } 242 | break; 243 | } 244 | } 245 | resultString = resourceString.substring(0, strNum - strGBKNum); 246 | if (isHaveDot) { 247 | resultString = resultString + "..."; 248 | } 249 | 250 | return resultString; 251 | } 252 | 253 | /** 254 | * 255 | * @autor:chenssy 256 | * @date:2014年8月10日 257 | * 258 | * @param htmlString 259 | * @param length 260 | * @return 261 | */ 262 | public static String subHTMLString(String htmlString,int length){ 263 | return subString(delHTMLTag(htmlString), length); 264 | } 265 | 266 | /** 267 | * 过滤html标签,包括script、style、html、空格、回车标签 268 | * @autor:chenssy 269 | * @date:2014年8月10日 270 | * 271 | * @param htmlStr 272 | * @return 273 | */ 274 | public static String delHTMLTag(String htmlStr){ 275 | String regEx_script = "]*?>[\\s\\S]*?<\\/script>"; // 定义script的正则表达式 276 | String regEx_style = "]*?>[\\s\\S]*?<\\/style>"; // 定义style的正则表达式 277 | String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式 278 | String regEx_space = "\\s*|\t|\r|\n";//定义空格回车换行符 279 | 280 | Pattern p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE); 281 | Matcher m_script = p_script.matcher(htmlStr); 282 | htmlStr = m_script.replaceAll(""); // 过滤script标签 283 | 284 | Pattern p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE); 285 | Matcher m_style = p_style.matcher(htmlStr); 286 | htmlStr = m_style.replaceAll(""); // 过滤style标签 287 | 288 | Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE); 289 | Matcher m_html = p_html.matcher(htmlStr); 290 | htmlStr = m_html.replaceAll(""); // 过滤html标签 291 | 292 | Pattern p_space = Pattern.compile(regEx_space, Pattern.CASE_INSENSITIVE); 293 | Matcher m_space = p_space.matcher(htmlStr); 294 | htmlStr = m_space.replaceAll(""); // 过滤空格回车标签 295 | 296 | return htmlStr.trim(); // 返回文本字符串 297 | } 298 | } 299 | -------------------------------------------------------------------------------- /src/main/java/com/JUtils/base/ValidateHelper.java: -------------------------------------------------------------------------------- 1 | package com.JUtils.base; 2 | 3 | import java.lang.reflect.Array; 4 | import java.util.Collection; 5 | import java.util.Date; 6 | import java.util.Map; 7 | 8 | /** 9 | * 判断对象、字符串、集合是否为空、不为空 10 | * 11 | * @Author:chenssy 12 | * @date:2014年8月4日 13 | */ 14 | public final class ValidateHelper { 15 | 16 | /** 17 | * 判断数组是否为空 18 | * @author chenssy 19 | * @date Dec 23, 2013 20 | * @param array 21 | * @return boolean 22 | */ 23 | @SuppressWarnings("unused") 24 | private static boolean isEmptyArray(T[] array){ 25 | if (array == null || array.length == 0){ 26 | return true; 27 | } 28 | else{ 29 | return false; 30 | } 31 | } 32 | 33 | /** 34 | * 判断数组是否不为空 35 | * @author chenssy 36 | * @date Dec 23, 2013 37 | * @param array 38 | * @return boolean 39 | */ 40 | public static boolean isNotEmptyArray(T[] array){ 41 | if (array != null && array.length > 0){ 42 | return true; 43 | } 44 | else{ 45 | return false; 46 | } 47 | } 48 | 49 | /** 50 | * 判断字符串是否为空 51 | * @author chenssy 52 | * @date Dec 23, 2013 53 | * @param string 54 | * @return boolean 55 | */ 56 | public static boolean isEmptyString(String string){ 57 | if (string == null || string.length() == 0){ 58 | return true; 59 | } 60 | else{ 61 | return false; 62 | } 63 | } 64 | 65 | /** 66 | * 判断字符串是否不为空 67 | * @author chenssy 68 | * @date Dec 23, 2013 69 | * @param string 70 | * @return boolean 71 | */ 72 | public static boolean isNotEmptyString(String string){ 73 | if (string != null && string.length() > 0){ 74 | return true; 75 | } 76 | else{ 77 | return false; 78 | } 79 | } 80 | 81 | /** 82 | * 判断集合是否为空 83 | * @author chenssy 84 | * @date Dec 26, 2013 85 | * @param collection 86 | * @return boolean 87 | */ 88 | public static boolean isEmptyCollection(Collection collection){ 89 | if (collection == null || collection.isEmpty()){ 90 | return true; 91 | } 92 | else{ 93 | return false; 94 | } 95 | } 96 | 97 | /** 98 | * 判断集合是否不为空 99 | * @author chenssy 100 | * @date Dec 26, 2013 101 | * @param collection 102 | * @return boolean 103 | */ 104 | public static boolean isNotEmptyCollection(Collection collection){ 105 | if (collection != null && !collection.isEmpty()){ 106 | return true; 107 | } 108 | else{ 109 | return false; 110 | } 111 | } 112 | 113 | /** 114 | * 判断map集合是否不为空 115 | * @author chenssy 116 | * @date Dec 26, 2013 117 | * @param map 118 | * @return boolean 119 | */ 120 | @SuppressWarnings("rawtypes") 121 | public static boolean isNotEmptyMap(Map map){ 122 | if (map != null && !map.isEmpty()){ 123 | return true; 124 | } 125 | else{ 126 | return false; 127 | } 128 | } 129 | 130 | /** 131 | * 判断map集合是否为空 132 | * @author ming.chen 133 | * @date Dec 26, 2013 134 | * @param map 135 | * @return boolean 136 | */ 137 | @SuppressWarnings("rawtypes") 138 | public static boolean isEmptyMap(Map map){ 139 | if (map == null || map.isEmpty()){ 140 | return true; 141 | } 142 | else{ 143 | return false; 144 | } 145 | } 146 | 147 | /** 148 | * 检验对象是否为空,String 中只有空格在对象中也算空. 149 | * @param object 150 | * @return 为空返回true,否则false. 151 | */ 152 | @SuppressWarnings("rawtypes") 153 | public static boolean isEmpty(Object object) { 154 | if (null == object) 155 | return true; 156 | else if (object instanceof String) 157 | return "".equals(object.toString().trim()); 158 | else if (object instanceof Iterable) 159 | return !((Iterable) object).iterator().hasNext(); 160 | else if (object.getClass().isArray()) 161 | return Array.getLength(object) == 0; 162 | else if (object instanceof Map) 163 | return ((Map) object).size() == 0; 164 | else if (Number.class.isAssignableFrom(object.getClass())) 165 | return false; 166 | else if (Date.class.isAssignableFrom(object.getClass())) 167 | return false; 168 | else 169 | return false; 170 | } 171 | } 172 | -------------------------------------------------------------------------------- /src/main/java/com/JUtils/beanConvert/BeanMapConvert.java: -------------------------------------------------------------------------------- 1 | package com.JUtils.beanConvert; 2 | 3 | import java.beans.BeanInfo; 4 | import java.beans.IntrospectionException; 5 | import java.beans.Introspector; 6 | import java.beans.PropertyDescriptor; 7 | import java.lang.reflect.InvocationTargetException; 8 | import java.lang.reflect.Method; 9 | import java.util.HashMap; 10 | import java.util.Map; 11 | 12 | /** 13 | * Bean与Map的转换 14 | * 15 | * @author chenssy 16 | * @date 2016-09-24 17 | * @since 1.0.0 18 | */ 19 | public class BeanMapConvert { 20 | /** 21 | * Bean转换为Map 22 | * 23 | * @param object 24 | * @return String-Object的HashMap 25 | * 26 | * @author chenssy 27 | * @date 2016-09-25 28 | * @since v1.0.0 29 | */ 30 | public static Map bean2MapObject(Object object){ 31 | if(object == null){ 32 | return null; 33 | } 34 | 35 | Map map = new HashMap(); 36 | try { 37 | BeanInfo beanInfo = Introspector.getBeanInfo(object.getClass()); 38 | PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); 39 | for (PropertyDescriptor property : propertyDescriptors) { 40 | String key = property.getName(); 41 | // 过滤class属性 42 | if (!key.equals("class")) { 43 | // 得到property对应的getter方法 44 | Method getter = property.getReadMethod(); 45 | Object value = getter.invoke(object); 46 | 47 | map.put(key, value); 48 | } 49 | } 50 | } catch (Exception e) { 51 | e.printStackTrace(); 52 | } 53 | 54 | return map; 55 | } 56 | 57 | /** 58 | * Map转换为Java Bean 59 | * 60 | * @param map 61 | * 待转换的Map 62 | * @param object 63 | * Java Bean 64 | * @return java.lang.Object 65 | * 66 | * @author chenssy 67 | * @date 2016-09-25 68 | * @since v1.0.0 69 | */ 70 | public static Object map2Bean(Map map,Object object){ 71 | if(map == null || object == null){ 72 | return null; 73 | } 74 | try { 75 | BeanInfo beanInfo = Introspector.getBeanInfo(object.getClass()); 76 | PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); 77 | 78 | for (PropertyDescriptor property : propertyDescriptors) { 79 | String key = property.getName(); 80 | if (map.containsKey(key)) { 81 | Object value = map.get(key); 82 | // 得到property对应的setter方法 83 | Method setter = property.getWriteMethod(); 84 | setter.invoke(object, value); 85 | } 86 | } 87 | } catch (IntrospectionException e) { 88 | e.printStackTrace(); 89 | } catch (InvocationTargetException e) { 90 | e.printStackTrace(); 91 | } catch (IllegalAccessException e) { 92 | e.printStackTrace(); 93 | } 94 | return object; 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /src/main/java/com/JUtils/clone/CloneUtils.java: -------------------------------------------------------------------------------- 1 | package com.JUtils.clone; 2 | 3 | import java.io.ByteArrayInputStream; 4 | import java.io.ByteArrayOutputStream; 5 | import java.io.IOException; 6 | import java.io.ObjectInputStream; 7 | import java.io.ObjectOutputStream; 8 | import java.io.Serializable; 9 | import java.util.Collection; 10 | 11 | /** 12 | * 克隆工具类,进行深克隆,包括对象、集合 13 | * 14 | * @Author:chenssy 15 | * @date:2014年8月9日 16 | */ 17 | public class CloneUtils { 18 | 19 | /** 20 | * 采用对象的序列化完成对象的深克隆 21 | * @autor:chenssy 22 | * @date:2014年8月9日 23 | * 24 | * @param obj 25 | * 待克隆的对象 26 | * @return 27 | */ 28 | @SuppressWarnings("unchecked") 29 | public static T cloneObject(T obj) { 30 | T cloneObj = null; 31 | try { 32 | // 写入字节流 33 | ByteArrayOutputStream out = new ByteArrayOutputStream(); 34 | ObjectOutputStream obs = new ObjectOutputStream(out); 35 | obs.writeObject(obj); 36 | obs.close(); 37 | 38 | // 分配内存,写入原始对象,生成新对象 39 | ByteArrayInputStream ios = new ByteArrayInputStream(out.toByteArray()); 40 | ObjectInputStream ois = new ObjectInputStream(ios); 41 | // 返回生成的新对象 42 | cloneObj = (T) ois.readObject(); 43 | ois.close(); 44 | } catch (Exception e) { 45 | e.printStackTrace(); 46 | } 47 | return cloneObj; 48 | } 49 | 50 | /** 51 | * 利用序列化完成集合的深克隆 52 | * @autor:chenssy 53 | * @date:2014年8月9日 54 | * 55 | * @param collection 56 | * 待克隆的集合 57 | * @return 58 | * @throws ClassNotFoundException 59 | * @throws java.io.IOException 60 | */ 61 | @SuppressWarnings("unchecked") 62 | public static Collection cloneCollection(Collection collection) throws ClassNotFoundException, IOException{ 63 | ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); 64 | ObjectOutputStream out = new ObjectOutputStream(byteOut); 65 | out.writeObject(collection); 66 | out.close(); 67 | 68 | ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray()); 69 | ObjectInputStream in = new ObjectInputStream(byteIn); 70 | Collection dest = (Collection) in.readObject(); 71 | in.close(); 72 | 73 | return dest; 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/main/java/com/JUtils/date/DateFormatUtils.java: -------------------------------------------------------------------------------- 1 | package com.JUtils.date; 2 | 3 | import java.text.ParsePosition; 4 | import java.text.SimpleDateFormat; 5 | import java.util.Date; 6 | 7 | /** 8 | * 日期格式化工具类 9 | * 10 | * @Author:chenssy 11 | * @date:2016年5月26日 下午12:39:57 12 | * 13 | */ 14 | public class DateFormatUtils { 15 | /** yyyy:年 */ 16 | public static final String DATE_YEAR = "yyyy"; 17 | 18 | /** MM:月 */ 19 | public static final String DATE_MONTH = "MM"; 20 | 21 | /** DD:日 */ 22 | public static final String DATE_DAY = "dd"; 23 | 24 | /** HH:时 */ 25 | public static final String DATE_HOUR = "HH"; 26 | 27 | /** mm:分 */ 28 | public static final String DATE_MINUTE = "mm"; 29 | 30 | /** ss:秒 */ 31 | public static final String DATE_SECONDES = "ss"; 32 | 33 | /** yyyy-MM-dd */ 34 | public static final String DATE_FORMAT1 = "yyyy-MM-dd"; 35 | 36 | /** yyyy-MM-dd hh:mm:ss */ 37 | public static final String DATE_FORMAT2 = "yyyy-MM-dd HH:mm:ss"; 38 | 39 | /** yyyy-MM-dd hh:mm:ss|SSS */ 40 | public static final String TIME_FORMAT_SSS = "yyyy-MM-dd HH:mm:ss|SSS"; 41 | 42 | /** yyyyMMdd */ 43 | public static final String DATE_NOFUll_FORMAT = "yyyyMMdd"; 44 | 45 | /** yyyyMMddhhmmss */ 46 | public static final String TIME_NOFUll_FORMAT = "yyyyMMddHHmmss"; 47 | 48 | /** 49 | * 50 | * 格式转换
51 | * yyyy-MM-dd hh:mm:ss 和 yyyyMMddhhmmss 相互转换
52 | * yyyy-mm-dd 和yyyymmss 相互转换 53 | * @author chenssy 54 | * @date Dec 26, 2013 55 | * @param value 56 | * 日期 57 | * @return String 58 | */ 59 | public static String formatString(String value) { 60 | String sReturn = ""; 61 | if (value == null || "".equals(value)) 62 | return sReturn; 63 | if (value.length() == 14) { //长度为14格式转换成yyyy-mm-dd hh:mm:ss 64 | sReturn = value.substring(0, 4) + "-" + value.substring(4, 6) + "-" + value.substring(6, 8) + " " 65 | + value.substring(8, 10) + ":" + value.substring(10, 12) + ":" + value.substring(12, 14); 66 | return sReturn; 67 | } 68 | if (value.length() == 19) { //长度为19格式转换成yyyymmddhhmmss 69 | sReturn = value.substring(0, 4) + value.substring(5, 7) + value.substring(8, 10) + value.substring(11, 13) 70 | + value.substring(14, 16) + value.substring(17, 19); 71 | return sReturn; 72 | } 73 | if(value.length() == 10){ //长度为10格式转换成yyyymmhh 74 | sReturn = value.substring(0, 4) + value.substring(5,7) + value.substring(8,10); 75 | } 76 | if(value.length() == 8){ //长度为8格式转化成yyyy-mm-dd 77 | sReturn = value.substring(0, 4) + "-" + value.substring(4, 6) + "-" + value.substring(6, 8); 78 | } 79 | return sReturn; 80 | } 81 | 82 | public static String formatDate(String date, String format) { 83 | if (date == null || "".equals(date)){ 84 | return ""; 85 | } 86 | Date dt = null; 87 | SimpleDateFormat inFmt = null; 88 | SimpleDateFormat outFmt = null; 89 | ParsePosition pos = new ParsePosition(0); 90 | date = date.replace("-", "").replace(":", ""); 91 | if ((date == null) || ("".equals(date.trim()))) 92 | return ""; 93 | try { 94 | if (Long.parseLong(date) == 0L) 95 | return ""; 96 | } catch (Exception nume) { 97 | return date; 98 | } 99 | try { 100 | switch (date.trim().length()) { 101 | case 14: 102 | inFmt = new SimpleDateFormat("yyyyMMddHHmmss"); 103 | break; 104 | case 12: 105 | inFmt = new SimpleDateFormat("yyyyMMddHHmm"); 106 | break; 107 | case 10: 108 | inFmt = new SimpleDateFormat("yyyyMMddHH"); 109 | break; 110 | case 8: 111 | inFmt = new SimpleDateFormat("yyyyMMdd"); 112 | break; 113 | case 6: 114 | inFmt = new SimpleDateFormat("yyyyMM"); 115 | break; 116 | case 7: 117 | case 9: 118 | case 11: 119 | case 13: 120 | default: 121 | return date; 122 | } 123 | if ((dt = inFmt.parse(date, pos)) == null) 124 | return date; 125 | if ((format == null) || ("".equals(format.trim()))) { 126 | outFmt = new SimpleDateFormat("yyyy年MM月dd日"); 127 | } else { 128 | outFmt = new SimpleDateFormat(format); 129 | } 130 | return outFmt.format(dt); 131 | } catch (Exception ex) { 132 | } 133 | return date; 134 | } 135 | 136 | /** 137 | * 格式化日期 138 | * 139 | * @author chenming 140 | * @date 2016年5月31日 141 | * 142 | * @param date 143 | * @param format 144 | * @return 145 | */ 146 | public static String formatDate(Date date,String format){ 147 | return formatDate(DateUtils.date2String(date), format); 148 | } 149 | 150 | /** 151 | * @desc:格式化是时间,采用默认格式(yyyy-MM-dd HH:mm:ss) 152 | * @autor:chenssy 153 | * @date:2014年8月6日 154 | * 155 | * @param value 156 | * @return 157 | */ 158 | public static String formatDate(String value){ 159 | return getFormat(DATE_FORMAT2).format(DateUtils.string2Date(value, DATE_FORMAT2)); 160 | } 161 | 162 | /** 163 | * 格式化日期 164 | * 165 | * @author : chenssy 166 | * @date : 2016年5月31日 下午5:40:58 167 | * 168 | * @param value 169 | * @return 170 | */ 171 | public static String formatDate(Date value){ 172 | return formatDate(DateUtils.date2String(value)); 173 | } 174 | 175 | /** 176 | * 获取日期显示格式,为空默认为yyyy-mm-dd HH:mm:ss 177 | * @author chenssy 178 | * @date Dec 30, 2013 179 | * @param format 180 | * @return 181 | * @return SimpleDateFormat 182 | */ 183 | protected static SimpleDateFormat getFormat(String format){ 184 | if(format == null || "".equals(format)){ 185 | format = DATE_FORMAT2; 186 | } 187 | return new SimpleDateFormat(format); 188 | } 189 | } 190 | -------------------------------------------------------------------------------- /src/main/java/com/JUtils/date/DateUtils.java: -------------------------------------------------------------------------------- 1 | package com.JUtils.date; 2 | 3 | import java.text.DateFormat; 4 | import java.text.ParseException; 5 | import java.text.SimpleDateFormat; 6 | import java.util.Calendar; 7 | import java.util.Date; 8 | 9 | /** 10 | * @desc:时间处理工具类 11 | * 12 | * @Author:chenssy 13 | * @date:2014年8月4日 14 | */ 15 | public class DateUtils { 16 | private static final String[] weeks = {"星期日","星期一","星期二","星期三","星期四","星期五","星期六"}; 17 | /** 18 | * 根据指定格式获取当前时间 19 | * @author chenssy 20 | * @date Dec 27, 2013 21 | * @param format 22 | * @return String 23 | */ 24 | public static String getCurrentTime(String format){ 25 | SimpleDateFormat sdf = DateFormatUtils.getFormat(format); 26 | Date date = new Date(); 27 | return sdf.format(date); 28 | } 29 | 30 | /** 31 | * 获取当前时间,格式为:yyyy-MM-dd HH:mm:ss 32 | * @author chenssy 33 | * @date Dec 27, 2013 34 | * @return String 35 | */ 36 | public static String getCurrentTime(){ 37 | return getCurrentTime(DateFormatUtils.DATE_FORMAT2); 38 | } 39 | 40 | /** 41 | * 获取指定格式的当前时间:为空时格式为yyyy-mm-dd HH:mm:ss 42 | * @author chenssy 43 | * @date Dec 30, 2013 44 | * @param format 45 | * @return Date 46 | */ 47 | public static Date getCurrentDate(String format){ 48 | SimpleDateFormat sdf = DateFormatUtils.getFormat(format); 49 | String dateS = getCurrentTime(format); 50 | Date date = null; 51 | try { 52 | date = sdf.parse(dateS); 53 | } catch (ParseException e) { 54 | e.printStackTrace(); 55 | } 56 | return date; 57 | } 58 | 59 | /** 60 | * 获取当前时间,格式为yyyy-MM-dd HH:mm:ss 61 | * @author chenssy 62 | * @date Dec 30, 2013 63 | * @return Date 64 | */ 65 | public static Date getCurrentDate(){ 66 | return getCurrentDate(DateFormatUtils.DATE_FORMAT2); 67 | } 68 | 69 | /** 70 | * 给指定日期加入年份,为空时默认当前时间 71 | * @author chenssy 72 | * @date Dec 30, 2013 73 | * @param year 年份 正数相加、负数相减 74 | * @param date 为空时,默认为当前时间 75 | * @param format 默认格式为:yyyy-MM-dd HH:mm:ss 76 | * @return String 77 | */ 78 | public static String addYearToDate(int year,Date date,String format){ 79 | Calendar calender = getCalendar(date,format); 80 | SimpleDateFormat sdf = DateFormatUtils.getFormat(format); 81 | 82 | calender.add(Calendar.YEAR, year); 83 | 84 | return sdf.format(calender.getTime()); 85 | } 86 | 87 | /** 88 | * 给指定日期加入年份,为空时默认当前时间 89 | * @author chenssy 90 | * @date Dec 30, 2013 91 | * @param year 年份 正数相加、负数相减 92 | * @param date 为空时,默认为当前时间 93 | * @param format 默认格式为:yyyy-MM-dd HH:mm:ss 94 | * @return String 95 | */ 96 | public static String addYearToDate(int year,String date,String format){ 97 | Date newDate = new Date(); 98 | if(null != date && !"".equals(date)){ 99 | newDate = string2Date(date, format); 100 | } 101 | 102 | return addYearToDate(year, newDate, format); 103 | } 104 | 105 | /** 106 | * 给指定日期增加月份 为空时默认当前时间 107 | * @author chenssy 108 | * @date Dec 30, 2013 109 | * @param month 增加月份 正数相加、负数相减 110 | * @param date 指定时间 111 | * @param format 指定格式 为空默认 yyyy-mm-dd HH:mm:ss 112 | * @return String 113 | */ 114 | public static String addMothToDate(int month,Date date,String format) { 115 | Calendar calender = getCalendar(date,format); 116 | SimpleDateFormat sdf = DateFormatUtils.getFormat(format); 117 | 118 | calender.add(Calendar.MONTH, month); 119 | 120 | return sdf.format(calender.getTime()); 121 | } 122 | 123 | /** 124 | * 给指定日期增加月份 为空时默认当前时间 125 | * @author chenssy 126 | * @date Dec 30, 2013 127 | * @param month 增加月份 正数相加、负数相减 128 | * @param date 指定时间 129 | * @param format 指定格式 为空默认 yyyy-mm-dd HH:mm:ss 130 | * @return String 131 | */ 132 | public static String addMothToDate(int month,String date,String format) { 133 | Date newDate = new Date(); 134 | if(null != date && !"".equals(date)){ 135 | newDate = string2Date(date, format); 136 | } 137 | 138 | return addMothToDate(month, newDate, format); 139 | } 140 | 141 | /** 142 | * 给指定日期增加天数,为空时默认当前时间 143 | * @author chenssy 144 | * @date Dec 31, 2013 145 | * @param day 增加天数 正数相加、负数相减 146 | * @param date 指定日期 147 | * @param format 日期格式 为空默认 yyyy-mm-dd HH:mm:ss 148 | * @return String 149 | */ 150 | public static String addDayToDate(int day,Date date,String format) { 151 | Calendar calendar = getCalendar(date, format); 152 | SimpleDateFormat sdf = DateFormatUtils.getFormat(format); 153 | 154 | calendar.add(Calendar.DATE, day); 155 | 156 | return sdf.format(calendar.getTime()); 157 | } 158 | 159 | /** 160 | * 给指定日期增加天数,为空时默认当前时间 161 | * @author chenssy 162 | * @date Dec 31, 2013 163 | * @param day 增加天数 正数相加、负数相减 164 | * @param date 指定日期 165 | * @param format 日期格式 为空默认 yyyy-mm-dd HH:mm:ss 166 | * @return String 167 | */ 168 | public static String addDayToDate(int day,String date,String format) { 169 | Date newDate = new Date(); 170 | if(null != date && !"".equals(date)){ 171 | newDate = string2Date(date, format); 172 | } 173 | 174 | return addDayToDate(day, newDate, format); 175 | } 176 | 177 | /** 178 | * 给指定日期增加小时,为空时默认当前时间 179 | * @author chenssy 180 | * @date Dec 31, 2013 181 | * @param hour 增加小时 正数相加、负数相减 182 | * @param date 指定日期 183 | * @param format 日期格式 为空默认 yyyy-mm-dd HH:mm:ss 184 | * @return String 185 | */ 186 | public static String addHourToDate(int hour,Date date,String format) { 187 | Calendar calendar = getCalendar(date, format); 188 | SimpleDateFormat sdf = DateFormatUtils.getFormat(format); 189 | 190 | calendar.add(Calendar.HOUR, hour); 191 | 192 | return sdf.format(calendar.getTime()); 193 | } 194 | 195 | /** 196 | * 给指定日期增加小时,为空时默认当前时间 197 | * @author chenssy 198 | * @date Dec 31, 2013 199 | * @param hour 增加小时 正数相加、负数相减 200 | * @param date 指定日期 201 | * @param format 日期格式 为空默认 yyyy-mm-dd HH:mm:ss 202 | * @return String 203 | */ 204 | public static String addHourToDate(int hour,String date,String format) { 205 | Date newDate = new Date(); 206 | if(null != date && !"".equals(date)){ 207 | newDate = string2Date(date, format); 208 | } 209 | 210 | return addHourToDate(hour, newDate, format); 211 | } 212 | 213 | /** 214 | * 给指定的日期增加分钟,为空时默认当前时间 215 | * @author chenssy 216 | * @date Dec 31, 2013 217 | * @param minute 增加分钟 正数相加、负数相减 218 | * @param date 指定日期 219 | * @param format 日期格式 为空默认 yyyy-mm-dd HH:mm:ss 220 | * @return String 221 | */ 222 | public static String addMinuteToDate(int minute,Date date,String format) { 223 | Calendar calendar = getCalendar(date, format); 224 | SimpleDateFormat sdf = DateFormatUtils.getFormat(format); 225 | 226 | calendar.add(Calendar.MINUTE, minute); 227 | 228 | return sdf.format(calendar.getTime()); 229 | } 230 | 231 | /** 232 | * 给指定的日期增加分钟,为空时默认当前时间 233 | * @author chenssy 234 | * @date Dec 31, 2013 235 | * @param minute 增加分钟 正数相加、负数相减 236 | * @param date 指定日期 237 | * @param format 日期格式 为空默认 yyyy-mm-dd HH:mm:ss 238 | * @return String 239 | */ 240 | public static String addMinuteToDate(int minute,String date,String format){ 241 | Date newDate = new Date(); 242 | if(null != date && !"".equals(date)){ 243 | newDate = string2Date(date, format); 244 | } 245 | 246 | return addMinuteToDate(minute, newDate, format); 247 | } 248 | 249 | /** 250 | * 给指定日期增加秒,为空时默认当前时间 251 | * @author chenssy 252 | * @date Dec 31, 2013 253 | * @param second 增加秒 正数相加、负数相减 254 | * @param date 指定日期 255 | * @param format 日期格式 为空默认 yyyy-mm-dd HH:mm:ss 256 | * @return String 257 | */ 258 | public static String addSecondToDate(int second,Date date,String format){ 259 | Calendar calendar = getCalendar(date, format); 260 | SimpleDateFormat sdf = DateFormatUtils.getFormat(format); 261 | 262 | calendar.add(Calendar.SECOND, second); 263 | 264 | return sdf.format(calendar.getTime()); 265 | } 266 | 267 | /** 268 | * 给指定日期增加秒,为空时默认当前时间 269 | * @author chenssy 270 | * @date Dec 31, 2013 271 | * @param second 增加秒 正数相加、负数相减 272 | * @param date 指定日期 273 | * @param format 日期格式 为空默认 yyyy-mm-dd HH:mm:ss 274 | * @return String 275 | * @throws Exception 276 | */ 277 | public static String addSecondToDate(int second,String date,String format){ 278 | Date newDate = new Date(); 279 | if(null != date && !"".equals(date)){ 280 | newDate = string2Date(date, format); 281 | } 282 | 283 | return addSecondToDate(second, newDate, format); 284 | } 285 | 286 | /** 287 | * 获取指定格式指定时间的日历 288 | * @author chenssy 289 | * @date Dec 30, 2013 290 | * @param date 时间 291 | * @param format 格式 292 | * @return Calendar 293 | */ 294 | public static Calendar getCalendar(Date date,String format){ 295 | if(date == null){ 296 | date = getCurrentDate(format); 297 | } 298 | 299 | Calendar calender = Calendar.getInstance(); 300 | calender.setTime(date); 301 | 302 | return calender; 303 | } 304 | 305 | /** 306 | * 字符串转换为日期,日期格式为 307 | * 308 | * @author : chenssy 309 | * @date : 2016年5月31日 下午5:20:22 310 | * 311 | * @param value 312 | * @return 313 | */ 314 | public static Date string2Date(String value){ 315 | if(value == null || "".equals(value)){ 316 | return null; 317 | } 318 | 319 | SimpleDateFormat sdf = DateFormatUtils.getFormat(DateFormatUtils.DATE_FORMAT2); 320 | Date date = null; 321 | 322 | try { 323 | value = DateFormatUtils.formatDate(value, DateFormatUtils.DATE_FORMAT2); 324 | date = sdf.parse(value); 325 | } catch (Exception e) { 326 | e.printStackTrace(); 327 | } 328 | return date; 329 | } 330 | 331 | /** 332 | * 将字符串(格式符合规范)转换成Date 333 | * @author chenssy 334 | * @date Dec 31, 2013 335 | * @param value 需要转换的字符串 336 | * @param format 日期格式 337 | * @return Date 338 | */ 339 | public static Date string2Date(String value,String format){ 340 | if(value == null || "".equals(value)){ 341 | return null; 342 | } 343 | 344 | SimpleDateFormat sdf = DateFormatUtils.getFormat(format); 345 | Date date = null; 346 | 347 | try { 348 | value = DateFormatUtils.formatDate(value, format); 349 | date = sdf.parse(value); 350 | } catch (Exception e) { 351 | e.printStackTrace(); 352 | } 353 | return date; 354 | } 355 | 356 | /** 357 | * 将日期格式转换成String 358 | * @author chenssy 359 | * @date Dec 31, 2013 360 | * 361 | * @param value 需要转换的日期 362 | * @param format 日期格式 363 | * @return String 364 | */ 365 | public static String date2String(Date value,String format){ 366 | if(value == null){ 367 | return null; 368 | } 369 | 370 | SimpleDateFormat sdf = DateFormatUtils.getFormat(format); 371 | return sdf.format(value); 372 | } 373 | 374 | /** 375 | * 日期转换为字符串 376 | * 377 | * @author : chenssy 378 | * @date : 2016年5月31日 下午5:21:38 379 | * 380 | * @param value 381 | * @return 382 | */ 383 | public static String date2String(Date value){ 384 | if(value == null){ 385 | return null; 386 | } 387 | 388 | SimpleDateFormat sdf = DateFormatUtils.getFormat(DateFormatUtils.DATE_FORMAT2); 389 | return sdf.format(value); 390 | } 391 | 392 | /** 393 | * 获取指定日期的年份 394 | * @author chenssy 395 | * @date Dec 31, 2013 396 | * @param value 日期 397 | * @return int 398 | */ 399 | public static int getCurrentYear(Date value){ 400 | String date = date2String(value, DateFormatUtils.DATE_YEAR); 401 | return Integer.valueOf(date); 402 | } 403 | 404 | /** 405 | * 获取指定日期的年份 406 | * @author chenssy 407 | * @date Dec 31, 2013 408 | * @param value 日期 409 | * @return int 410 | */ 411 | public static int getCurrentYear(String value) { 412 | Date date = string2Date(value, DateFormatUtils.DATE_YEAR); 413 | Calendar calendar = getCalendar(date, DateFormatUtils.DATE_YEAR); 414 | return calendar.get(Calendar.YEAR); 415 | } 416 | 417 | /** 418 | * 获取指定日期的月份 419 | * @author chenssy 420 | * @date Dec 31, 2013 421 | * @param value 日期 422 | * @return int 423 | */ 424 | public static int getCurrentMonth(Date value){ 425 | String date = date2String(value, DateFormatUtils.DATE_MONTH); 426 | return Integer.valueOf(date); 427 | } 428 | 429 | /** 430 | * 获取指定日期的月份 431 | * @author chenssy 432 | * @date Dec 31, 2013 433 | * @param value 日期 434 | * @return int 435 | */ 436 | public static int getCurrentMonth(String value) { 437 | Date date = string2Date(value, DateFormatUtils.DATE_MONTH); 438 | Calendar calendar = getCalendar(date, DateFormatUtils.DATE_MONTH); 439 | 440 | return calendar.get(Calendar.MONTH); 441 | } 442 | 443 | /** 444 | * 获取指定日期的天份 445 | * @author chenssy 446 | * @date Dec 31, 2013 447 | * @param value 日期 448 | * @return int 449 | */ 450 | public static int getCurrentDay(Date value){ 451 | String date = date2String(value, DateFormatUtils.DATE_DAY); 452 | return Integer.valueOf(date); 453 | } 454 | 455 | /** 456 | * 获取指定日期的天份 457 | * @author chenssy 458 | * @date Dec 31, 2013 459 | * @param value 日期 460 | * @return int 461 | */ 462 | public static int getCurrentDay(String value){ 463 | Date date = string2Date(value, DateFormatUtils.DATE_DAY); 464 | Calendar calendar = getCalendar(date, DateFormatUtils.DATE_DAY); 465 | 466 | return calendar.get(Calendar.DATE); 467 | } 468 | 469 | /** 470 | * 获取当前日期为星期几 471 | * @author chenssy 472 | * @date Dec 31, 2013 473 | * @param value 日期 474 | * @return String 475 | */ 476 | public static String getCurrentWeek(Date value) { 477 | Calendar calendar = getCalendar(value, DateFormatUtils.DATE_FORMAT1); 478 | int weekIndex = calendar.get(Calendar.DAY_OF_WEEK) - 1 < 0 ? 0 : calendar.get(Calendar.DAY_OF_WEEK) - 1; 479 | 480 | return weeks[weekIndex]; 481 | } 482 | 483 | /** 484 | * 获取当前日期为星期几 485 | * @author chenssy 486 | * @date Dec 31, 2013 487 | * @param value 日期 488 | * @return String 489 | */ 490 | public static String getCurrentWeek(String value) { 491 | Date date = string2Date(value, DateFormatUtils.DATE_FORMAT1); 492 | return getCurrentWeek(date); 493 | } 494 | 495 | /** 496 | * 获取指定日期的小时 497 | * @author chenssy 498 | * @date Dec 31, 2013 499 | * @param value 日期 500 | * @return int 501 | */ 502 | public static int getCurrentHour(Date value){ 503 | String date = date2String(value, DateFormatUtils.DATE_HOUR); 504 | return Integer.valueOf(date); 505 | } 506 | 507 | /** 508 | * 获取指定日期的小时 509 | * @author chenssy 510 | * @date Dec 31, 2013 511 | * @param value 日期 512 | * @return 513 | * @return int 514 | */ 515 | public static int getCurrentHour(String value) { 516 | Date date = string2Date(value, DateFormatUtils.DATE_HOUR); 517 | Calendar calendar = getCalendar(date, DateFormatUtils.DATE_HOUR); 518 | 519 | return calendar.get(Calendar.DATE); 520 | } 521 | 522 | /** 523 | * 获取指定日期的分钟 524 | * @author chenssy 525 | * @date Dec 31, 2013 526 | * @param value 日期 527 | * @return int 528 | */ 529 | public static int getCurrentMinute(Date value){ 530 | String date = date2String(value, DateFormatUtils.DATE_MINUTE); 531 | return Integer.valueOf(date); 532 | } 533 | 534 | /** 535 | * 获取指定日期的分钟 536 | * @author chenssy 537 | * @date Dec 31, 2013 538 | * @param value 日期 539 | * @return int 540 | */ 541 | public static int getCurrentMinute(String value){ 542 | Date date = string2Date(value, DateFormatUtils.DATE_MINUTE); 543 | Calendar calendar = getCalendar(date, DateFormatUtils.DATE_MINUTE); 544 | 545 | return calendar.get(Calendar.MINUTE); 546 | } 547 | 548 | /** 549 | * 比较两个日期相隔多少天(月、年)
550 | * 例:
551 | *  compareDate("2009-09-12", null, 0);//比较天
552 | *  compareDate("2009-09-12", null, 1);//比较月
553 | *  compareDate("2009-09-12", null, 2);//比较年
554 | * 555 | * @author chenssy 556 | * @date Dec 31, 2013 557 | * @param startDay 需要比较的时间 不能为空(null),需要正确的日期格式 ,如:2009-09-12 558 | * @param endDay 被比较的时间 为空(null)则为当前时间 559 | * @param stype 返回值类型 0为多少天,1为多少个月,2为多少年 560 | * @return int 561 | */ 562 | public static int compareDate(String startDay,String endDay,int stype) { 563 | int n = 0; 564 | startDay = DateFormatUtils.formatDate(startDay, "yyyy-MM-dd"); 565 | endDay = DateFormatUtils.formatDate(endDay, "yyyy-MM-dd"); 566 | 567 | String formatStyle = "yyyy-MM-dd"; 568 | if(1 == stype){ 569 | formatStyle = "yyyy-MM"; 570 | }else if(2 == stype){ 571 | formatStyle = "yyyy"; 572 | } 573 | 574 | endDay = endDay==null ? getCurrentTime("yyyy-MM-dd") : endDay; 575 | 576 | DateFormat df = new SimpleDateFormat(formatStyle); 577 | Calendar c1 = Calendar.getInstance(); 578 | Calendar c2 = Calendar.getInstance(); 579 | try { 580 | c1.setTime(df.parse(startDay)); 581 | c2.setTime(df.parse(endDay)); 582 | } catch (Exception e) { 583 | e.printStackTrace(); 584 | } 585 | while (!c1.after(c2)) { // 循环对比,直到相等,n 就是所要的结果 586 | n++; 587 | if(stype==1){ 588 | c1.add(Calendar.MONTH, 1); // 比较月份,月份+1 589 | } 590 | else{ 591 | c1.add(Calendar.DATE, 1); // 比较天数,日期+1 592 | } 593 | } 594 | n = n-1; 595 | if(stype==2){ 596 | n = (int)n/365; 597 | } 598 | return n; 599 | } 600 | 601 | /** 602 | * 比较两个时间相差多少小时(分钟、秒) 603 | * @author chenssy 604 | * @date Jan 2, 2014 605 | * @param startTime 需要比较的时间 不能为空,且必须符合正确格式:2012-12-12 12:12: 606 | * @param endTime 需要被比较的时间 若为空则默认当前时间 607 | * @param type 1:小时 2:分钟 3:秒 608 | * @return int 609 | */ 610 | public static int compareTime(String startTime , String endTime , int type) { 611 | //endTime是否为空,为空默认当前时间 612 | if(endTime == null || "".equals(endTime)){ 613 | endTime = getCurrentTime(); 614 | } 615 | 616 | SimpleDateFormat sdf = DateFormatUtils.getFormat(""); 617 | int value = 0; 618 | try { 619 | Date begin = sdf.parse(startTime); 620 | Date end = sdf.parse(endTime); 621 | long between = (end.getTime() - begin.getTime()) / 1000; //除以1000转换成豪秒 622 | if(type == 1){ //小时 623 | value = (int) (between % (24 * 36000) / 3600); 624 | } 625 | else if(type == 2){ 626 | value = (int) (between % 3600 / 60); 627 | } 628 | else if(type == 3){ 629 | value = (int) (between % 60 / 60); 630 | } 631 | } catch (ParseException e) { 632 | e.printStackTrace(); 633 | } 634 | return value; 635 | } 636 | 637 | /** 638 | * 比较两个日期的大小。
639 | * 若date1 > date2 则返回 1
640 | * 若date1 = date2 则返回 0
641 | * 若date1 < date2 则返回-1 642 | * @autor:chenssy 643 | * @date:2014年9月9日 644 | * 645 | * @param date1 646 | * @param date2 647 | * @param format 待转换的格式 648 | * @return 比较结果 649 | */ 650 | public static int compare(String date1, String date2,String format) { 651 | DateFormat df = DateFormatUtils.getFormat(format); 652 | try { 653 | Date dt1 = df.parse(date1); 654 | Date dt2 = df.parse(date2); 655 | if (dt1.getTime() > dt2.getTime()) { 656 | return 1; 657 | } else if (dt1.getTime() < dt2.getTime()) { 658 | return -1; 659 | } else { 660 | return 0; 661 | } 662 | } catch (Exception exception) { 663 | exception.printStackTrace(); 664 | } 665 | return 0; 666 | } 667 | 668 | /** 669 | * 获取指定月份的第一天 670 | * 671 | * @author : chenssy 672 | * @date : 2016年5月31日 下午5:31:10 673 | * 674 | * @param date 675 | * @return 676 | */ 677 | public static String getMonthFirstDate(String date){ 678 | date = DateFormatUtils.formatDate(date); 679 | return DateFormatUtils.formatDate(date, "yyyy-MM") + "-01"; 680 | } 681 | 682 | /** 683 | * 获取指定月份的最后一天 684 | * 685 | * @author : chenssy 686 | * @date : 2016年5月31日 下午5:32:09 687 | * 688 | * @param strdate 689 | * @return 690 | */ 691 | public static String getMonthLastDate(String date) { 692 | Date strDate = DateUtils.string2Date(getMonthFirstDate(date)); 693 | Calendar calendar = Calendar.getInstance(); 694 | calendar.setTime(strDate); 695 | calendar.add(Calendar.MONTH, 1); 696 | calendar.add(Calendar.DAY_OF_YEAR, -1); 697 | return DateFormatUtils.formatDate(calendar.getTime()); 698 | } 699 | 700 | /** 701 | * 获取所在星期的第一天 702 | * 703 | * @author : chenssy 704 | * @date : 2016年6月1日 下午12:38:53 705 | * 706 | * @param date 707 | * @return 708 | */ 709 | @SuppressWarnings("static-access") 710 | public static Date getWeekFirstDate(Date date) { 711 | Calendar now = Calendar.getInstance(); 712 | now.setTime(date); 713 | int today = now.get(Calendar.DAY_OF_WEEK); 714 | int first_day_of_week = now.get(Calendar.DATE) + 2 - today; // 星期一 715 | now.set(now.DATE, first_day_of_week); 716 | return now.getTime(); 717 | } 718 | 719 | /** 720 | * 获取所在星期的最后一天 721 | * 722 | * @author : chenssy 723 | * @date : 2016年6月1日 下午12:40:31 724 | * 725 | * @param date 726 | * @return 727 | */ 728 | @SuppressWarnings("static-access") 729 | public static Date geWeektLastDate(Date date) { 730 | Calendar now = Calendar.getInstance(); 731 | now.setTime(date); 732 | int today = now.get(Calendar.DAY_OF_WEEK); 733 | int first_day_of_week = now.get(Calendar.DATE) + 2 - today; // 星期一 734 | int last_day_of_week = first_day_of_week + 6; // 星期日 735 | now.set(now.DATE, last_day_of_week); 736 | return now.getTime(); 737 | } 738 | } 739 | -------------------------------------------------------------------------------- /src/main/java/com/JUtils/date/TimestampUtils.java: -------------------------------------------------------------------------------- 1 | package com.JUtils.date; 2 | 3 | import java.sql.Timestamp; 4 | import java.text.SimpleDateFormat; 5 | import java.util.Date; 6 | 7 | /** 8 | * TimeStamp工具类,提供TimeStamp与String、Date的转换 9 | * 10 | * @author chenssy 11 | * @date 2016-09-24 12 | * @since 1.0.0 13 | */ 14 | public class TimestampUtils { 15 | 16 | /** 17 | * String转换为TimeStamp 18 | * @param value 19 | * 待转换的String,格式必须为 yyyy-mm-dd hh:mm:ss[.f...] 这样的格式,中括号表示可选,否则报错 20 | * @return java.sql.Timestamp 21 | * 22 | * @author chenssy 23 | * @date 2016-09-24 24 | * @since v1.0.0 25 | */ 26 | public static Timestamp string2Timestamp(String value){ 27 | if(value == null && !"".equals(value.trim())){ 28 | return null; 29 | } 30 | Timestamp ts = new Timestamp(System.currentTimeMillis()); 31 | ts = Timestamp.valueOf(value); 32 | return ts; 33 | } 34 | 35 | /** 36 | * 将Timestamp 转换为String类型,format为null则使用默认格式 yyyy-MM-dd HH:mm:ss 37 | * 38 | * @param value 39 | * 待转换的Timestamp 40 | * @param format 41 | * String的格式 42 | * @return java.lang.String 43 | * 44 | * @author chenssy 45 | * @date 2016-09-24 46 | * @since v1.0.0 47 | */ 48 | public static String timestamp2String(Timestamp value,String format){ 49 | if(null == value){ 50 | return ""; 51 | } 52 | SimpleDateFormat sdf = DateFormatUtils.getFormat(format); 53 | 54 | return sdf.format(value); 55 | } 56 | 57 | /** 58 | * Date转换为Timestamp 59 | * 60 | * @param date 61 | * 待转换的Date 62 | * @return java.sql.Timestamp 63 | * 64 | * @author chenssy 65 | * @date 2016-09-24 66 | * @since v1.0.0 67 | */ 68 | public static Timestamp date2Timestamp(Date date){ 69 | if(date == null){ 70 | return null; 71 | } 72 | return new Timestamp(date.getTime()); 73 | } 74 | 75 | /** 76 | * Timestamp转换为Date 77 | * 78 | * @param time 79 | * 待转换的Timestamp 80 | * @return java.util.Date 81 | * 82 | * @author chenssy 83 | * @date 2016-09-24 84 | * @since v1.0.0 85 | */ 86 | public static Date timestamp2Date(Timestamp time){ 87 | return time == null ? null : time; 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /src/main/java/com/JUtils/encrypt/AESUtils.java: -------------------------------------------------------------------------------- 1 | package com.JUtils.encrypt; 2 | 3 | import java.security.SecureRandom; 4 | 5 | import javax.crypto.Cipher; 6 | import javax.crypto.KeyGenerator; 7 | import javax.crypto.spec.SecretKeySpec; 8 | 9 | 10 | /** 11 | * AES加解密 12 | * 13 | * @Author:chenssy 14 | * @date:2016年5月21日 上午9:01:41 15 | */ 16 | class AESUtils { 17 | /** 默认秘钥 */ 18 | protected static final String KEY = "NOPO3nzMD3dndwS0MccuMeXCHgVlGOoYyFwLdS24Im2e7YyhB0wrUsyYf0"; 19 | 20 | /** 21 | * AES解密 22 | * 23 | * @author:chenssy 24 | * @date : 2016年5月21日 上午9:48:12 25 | * 26 | * @param encryptValue 27 | * 待解密内容 28 | * @param key 29 | * 秘钥 30 | * @return 31 | * @throws Exception 32 | */ 33 | protected static String decrypt(String encryptValue, String key) throws Exception { 34 | return aesDecryptByBytes(base64Decode(encryptValue), key); 35 | } 36 | 37 | /** 38 | * AES加密 39 | * 40 | * @author:chenssy 41 | * @date : 2016年5月21日 上午9:48:42 42 | * 43 | * @param value 44 | * 待加密内容 45 | * @param key 46 | * 秘钥 47 | * @return 48 | * @throws Exception 49 | */ 50 | protected static String encrypt(String value, String key) throws Exception { 51 | return base64Encode(aesEncryptToBytes(value, key)); 52 | } 53 | 54 | private static String base64Encode(byte[] bytes){ 55 | return Base64Utils.encrypt(bytes); 56 | } 57 | 58 | @SuppressWarnings("static-access") 59 | private static byte[] base64Decode(String base64Code) throws Exception{ 60 | return base64Code == null ? null : new Base64Utils().decrypt(base64Code); 61 | } 62 | 63 | private static byte[] aesEncryptToBytes(String content, String encryptKey) throws Exception { 64 | KeyGenerator kgen = KeyGenerator.getInstance("AES"); 65 | kgen.init(128, new SecureRandom(encryptKey.getBytes())); 66 | 67 | Cipher cipher = Cipher.getInstance("AES"); 68 | cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(kgen.generateKey().getEncoded(), "AES")); 69 | 70 | return cipher.doFinal(content.getBytes("utf-8")); 71 | } 72 | 73 | private static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey) throws Exception { 74 | KeyGenerator kgen = KeyGenerator.getInstance("AES"); 75 | kgen.init(128, new SecureRandom(decryptKey.getBytes())); 76 | 77 | Cipher cipher = Cipher.getInstance("AES"); 78 | cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(kgen.generateKey().getEncoded(), "AES")); 79 | byte[] decryptBytes = cipher.doFinal(encryptBytes); 80 | 81 | return new String(decryptBytes); 82 | } 83 | 84 | } 85 | -------------------------------------------------------------------------------- /src/main/java/com/JUtils/encrypt/Base64Utils.java: -------------------------------------------------------------------------------- 1 | package com.JUtils.encrypt; 2 | 3 | import java.io.UnsupportedEncodingException; 4 | 5 | /** 6 | * BASE64加解密工具类 7 | * 8 | * @Author:chenssy 9 | * @date:2016年5月20日 下午5:05:30 10 | * 11 | */ 12 | class Base64Utils { 13 | 14 | private static char[] base64EncodeChars = new char[] { 'A', 'B', 'C', 'D', 15 | 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 16 | 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 17 | 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 18 | 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', 19 | '4', '5', '6', '7', '8', '9', '+', '/' }; 20 | 21 | private static byte[] base64DecodeChars = new byte[] { -1, -1, -1, -1, -1, 22 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 23 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 24 | -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 25 | 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 26 | 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, 27 | -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 28 | 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, 29 | -1, -1 }; 30 | 31 | /** 32 | * BASE64加密 33 | * 34 | * @author : chenssy 35 | * @date : 2016年5月20日 下午5:10:18 36 | * 37 | * @param data 38 | * @return 39 | */ 40 | protected static String encrypt(byte[] data) { 41 | StringBuffer sb = new StringBuffer(); 42 | int len = data.length; 43 | int i = 0; 44 | int b1, b2, b3; 45 | while (i < len) { 46 | b1 = data[i++] & 0xff; 47 | if (i == len) { 48 | sb.append(base64EncodeChars[b1 >>> 2]); 49 | sb.append(base64EncodeChars[(b1 & 0x3) << 4]); 50 | sb.append("=="); 51 | break; 52 | } 53 | b2 = data[i++] & 0xff; 54 | if (i == len) { 55 | sb.append(base64EncodeChars[b1 >>> 2]); 56 | sb.append(base64EncodeChars[((b1 & 0x03) << 4) 57 | | ((b2 & 0xf0) >>> 4)]); 58 | sb.append(base64EncodeChars[(b2 & 0x0f) << 2]); 59 | sb.append("="); 60 | break; 61 | } 62 | b3 = data[i++] & 0xff; 63 | sb.append(base64EncodeChars[b1 >>> 2]); 64 | sb.append(base64EncodeChars[((b1 & 0x03) << 4) 65 | | ((b2 & 0xf0) >>> 4)]); 66 | sb.append(base64EncodeChars[((b2 & 0x0f) << 2) 67 | | ((b3 & 0xc0) >>> 6)]); 68 | sb.append(base64EncodeChars[b3 & 0x3f]); 69 | } 70 | return sb.toString(); 71 | } 72 | 73 | /** 74 | * Base64 解密 75 | * 76 | * @author : chenssy 77 | * @date : 2016年5月20日 下午5:11:51 78 | * 79 | * @param str 80 | * @return 81 | * @throws java.io.UnsupportedEncodingException 82 | */ 83 | protected static byte[] decrypt(String str) throws Exception{ 84 | StringBuffer sb = new StringBuffer(); 85 | byte[] data = str.getBytes("US-ASCII"); 86 | int len = data.length; 87 | int i = 0; 88 | int b1, b2, b3, b4; 89 | while (i < len) { 90 | 91 | do { 92 | b1 = base64DecodeChars[data[i++]]; 93 | } while (i < len && b1 == -1); 94 | if (b1 == -1) 95 | break; 96 | 97 | do { 98 | b2 = base64DecodeChars[data[i++]]; 99 | } while (i < len && b2 == -1); 100 | if (b2 == -1) 101 | break; 102 | sb.append((char) ((b1 << 2) | ((b2 & 0x30) >>> 4))); 103 | 104 | do { 105 | b3 = data[i++]; 106 | if (b3 == 61) 107 | return sb.toString().getBytes("iso8859-1"); 108 | b3 = base64DecodeChars[b3]; 109 | } while (i < len && b3 == -1); 110 | if (b3 == -1) 111 | break; 112 | sb.append((char) (((b2 & 0x0f) << 4) | ((b3 & 0x3c) >>> 2))); 113 | 114 | do { 115 | b4 = data[i++]; 116 | if (b4 == 61) 117 | return sb.toString().getBytes("iso8859-1"); 118 | b4 = base64DecodeChars[b4]; 119 | } while (i < len && b4 == -1); 120 | if (b4 == -1) 121 | break; 122 | sb.append((char) (((b3 & 0x03) << 6) | b4)); 123 | } 124 | return sb.toString().getBytes("iso8859-1"); 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /src/main/java/com/JUtils/encrypt/DESUtils.java: -------------------------------------------------------------------------------- 1 | package com.JUtils.encrypt; 2 | 3 | import java.security.SecureRandom; 4 | 5 | import javax.crypto.Cipher; 6 | import javax.crypto.SecretKey; 7 | import javax.crypto.SecretKeyFactory; 8 | import javax.crypto.spec.DESKeySpec; 9 | 10 | /** 11 | * DES加解密工具类 12 | * 13 | * @Author:chenssy 14 | * @date:2016年5月20日 下午5:19:00 15 | * 16 | */ 17 | class DESUtils { 18 | /** 默认key */ 19 | protected final static String KEY = "ScAKC0XhadTHT3Al0QIDAQAB"; 20 | 21 | /** 22 | * DES加密 23 | * 24 | * @author : chenssy 25 | * @date : 2016年5月20日 下午5:51:37 26 | * 27 | * @param data 28 | * 待加密字符串 29 | * @param key 30 | * 校验位 31 | * @return 32 | */ 33 | @SuppressWarnings("restriction") 34 | protected static String encrypt(String data,String key) { 35 | String encryptedData = null; 36 | try { 37 | // DES算法要求有一个可信任的随机数源 38 | SecureRandom sr = new SecureRandom(); 39 | DESKeySpec deskey = new DESKeySpec(key.getBytes()); 40 | // 创建一个密匙工厂,然后用它把DESKeySpec转换成一个SecretKey对象 41 | SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); 42 | SecretKey secretKey = keyFactory.generateSecret(deskey); 43 | // 加密对象 44 | Cipher cipher = Cipher.getInstance("DES"); 45 | cipher.init(Cipher.ENCRYPT_MODE, secretKey, sr); 46 | // 加密,并把字节数组编码成字符串 47 | encryptedData = new sun.misc.BASE64Encoder().encode(cipher.doFinal(data.getBytes())); 48 | } catch (Exception e) { 49 | throw new RuntimeException("加密错误,错误信息:", e); 50 | } 51 | return encryptedData; 52 | } 53 | 54 | /** 55 | * DES解密 56 | * 57 | * @author : chenssy 58 | * @date : 2016年5月20日 下午5:52:23 59 | * 60 | * @param cryptData 61 | * 待解密密文 62 | * @param key 63 | * 校验位 64 | * @return 65 | */ 66 | @SuppressWarnings("restriction") 67 | protected static String decrypt(String cryptData,String key) { 68 | String decryptedData = null; 69 | try { 70 | // DES算法要求有一个可信任的随机数源 71 | SecureRandom sr = new SecureRandom(); 72 | DESKeySpec deskey = new DESKeySpec(key.getBytes()); 73 | // 创建一个密匙工厂,然后用它把DESKeySpec转换成一个SecretKey对象 74 | SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); 75 | SecretKey secretKey = keyFactory.generateSecret(deskey); 76 | // 解密对象 77 | Cipher cipher = Cipher.getInstance("DES"); 78 | cipher.init(Cipher.DECRYPT_MODE, secretKey, sr); 79 | // 把字符串解码为字节数组,并解密 80 | decryptedData = new String(cipher.doFinal(new sun.misc.BASE64Decoder().decodeBuffer(cryptData))); 81 | } catch (Exception e) { 82 | throw new RuntimeException("解密错误,错误信息:", e); 83 | } 84 | return decryptedData; 85 | } 86 | 87 | } 88 | -------------------------------------------------------------------------------- /src/main/java/com/JUtils/encrypt/EncryptAndDecryptUtils.java: -------------------------------------------------------------------------------- 1 | package com.JUtils.encrypt; 2 | 3 | 4 | /** 5 | * 加解密工具类
6 | * 工具类包括:MD5加密、SHA加密、Base64加解密、DES加解密、AES加解密
7 | * 8 | * @Author:chenssy 9 | * @date:2016年5月20日 下午4:44:51 10 | * 11 | */ 12 | public class EncryptAndDecryptUtils { 13 | 14 | /** 15 | * MD5 加密 16 | * 17 | * @author : chenssy 18 | * @date : 2016年5月20日 下午4:54:23 19 | * 20 | * @param value 21 | * 待加密字符 22 | * @return 23 | */ 24 | public static String md5Encrypt(String value){ 25 | String result = null; 26 | if(value != null && !"".equals(value.trim())){ 27 | result = MD5Utils.encrypt(value,MD5Utils.MD5_KEY); 28 | } 29 | return result; 30 | } 31 | 32 | /** 33 | * SHA加密 34 | * 35 | * @author : chenssy 36 | * @date : 2016年5月20日 下午4:59:42 37 | * 38 | * @param value 39 | * 待加密字符 40 | * @return 密文 41 | */ 42 | public static String shaEncrypt(String value){ 43 | String result = null; 44 | if(value != null && !"".equals(value.trim())){ 45 | result = MD5Utils.encrypt(value,MD5Utils.SHA_KEY); 46 | } 47 | return result; 48 | } 49 | 50 | /** 51 | * BASE64 加密 52 | * 53 | * @author : chenssy 54 | * @date : 2016年5月20日 下午5:16:12 55 | * 56 | * @param value 57 | * 待加密字符串 58 | * @return 59 | */ 60 | public static String base64Encrypt(String value){ 61 | String result = null; 62 | if(value != null && !"".equals(value.trim())){ 63 | result = Base64Utils.encrypt(value.getBytes()); 64 | } 65 | return result; 66 | 67 | } 68 | 69 | /** 70 | * BASE64 解密 71 | * 72 | * @author : chenssy 73 | * @date : 2016年5月20日 下午5:16:34 74 | * 75 | * @param value 76 | * 待解密字符串 77 | * @return 78 | */ 79 | public static String base64Decrypt(String value){ 80 | String result = null; 81 | try { 82 | if(value != null && !"".equals(value.trim())){ 83 | byte[] bytes = Base64Utils.decrypt(value); 84 | result = new String(bytes); 85 | } 86 | } catch (Exception e) { 87 | e.printStackTrace(); 88 | } 89 | return result; 90 | } 91 | 92 | /** 93 | * DES加密
94 | * 95 | * @author : chenssy 96 | * @date : 2016年5月20日 下午5:39:46 97 | * 98 | * @param value 99 | * 待加密字符 100 | * @param key 101 | * 若key为空,则使用默认key 102 | * @return 103 | * 加密成功返回密文,否则返回null 104 | */ 105 | public static String desEncrypt(String value,String key){ 106 | key = key == null ? DESUtils.KEY : key; 107 | String result = null; 108 | 109 | try { 110 | if(value != null && !"".equals(value.trim())){ 111 | result = DESUtils.encrypt(value, key); 112 | } 113 | } catch (Exception e) { 114 | e.printStackTrace(); 115 | } 116 | return result; 117 | } 118 | 119 | /** 120 | * DES解密 121 | * 122 | * @author : chenssy 123 | * @date : 2016年5月20日 下午5:55:56 124 | * 125 | * @param value 126 | * 待解密字符 127 | * @param key 128 | * 若key为空,则使用默认key 129 | * @return 130 | * @return 131 | */ 132 | public static String desDecrypt(String value,String key){ 133 | key = key == null ? DESUtils.KEY : key; 134 | String result = null; 135 | 136 | try { 137 | if(value != null && !"".equals(value.trim())){ 138 | result = DESUtils.decrypt(value, key); 139 | } 140 | } catch (Exception e) { 141 | e.printStackTrace(); 142 | } 143 | return result; 144 | } 145 | 146 | /** 147 | * AES加密 148 | * 149 | * @author:chenssy 150 | * @date : 2016年5月21日 上午9:58:58 151 | * 152 | * @param value 153 | * 待加密内容 154 | * @param key 155 | * 秘钥 156 | * @return 157 | */ 158 | public static String aesEncrypt(String value,String key ){ 159 | key = key == null ? AESUtils.KEY : key; 160 | String result = null; 161 | try { 162 | if(value != null && !"".equals(value.trim())){ //value is not null 163 | result = AESUtils.encrypt(value,key); 164 | } 165 | } catch (Exception e) { 166 | e.printStackTrace(); 167 | } 168 | 169 | return result; 170 | } 171 | 172 | /** 173 | * AES解密 174 | * 175 | * @author:chenssy 176 | * @date : 2016年5月21日 上午10:02:07 177 | * 178 | * @param value 179 | * 待解密内容 180 | * @param key 181 | * 秘钥 182 | * @return 183 | */ 184 | public static String aesDecrypt(String value , String key){ 185 | key = key == null ? AESUtils.KEY : key; 186 | String result = null; 187 | try { 188 | if(value != null && !"".equals(value.trim())){ //value is not null 189 | result = AESUtils.decrypt(value,key); 190 | } 191 | } catch (Exception e) { 192 | e.printStackTrace(); 193 | } 194 | 195 | return result; 196 | } 197 | } 198 | -------------------------------------------------------------------------------- /src/main/java/com/JUtils/encrypt/MD5Utils.java: -------------------------------------------------------------------------------- 1 | package com.JUtils.encrypt; 2 | 3 | import java.security.MessageDigest; 4 | import java.security.NoSuchAlgorithmException; 5 | 6 | /** 7 | * MD5加密 8 | * 9 | * @Author:chenssy 10 | * @date:2016年4月9日 11 | */ 12 | class MD5Utils { 13 | protected final static String MD5_KEY = "MD5"; 14 | 15 | protected final static String SHA_KEY = "SHA1"; 16 | 17 | protected static String encrypt(String value,String key) { 18 | try { 19 | // 拿到一个MD5转换器(如果想要SHA1参数换成”SHA1”) 20 | MessageDigest messageDigest = MessageDigest.getInstance(key); 21 | // 输入的字符串转换成字节数组 22 | byte[] inputByteArray = value.getBytes(); 23 | // inputByteArray是输入字符串转换得到的字节数组 24 | messageDigest.update(inputByteArray); 25 | // 转换并返回结果,也是字节数组,包含16个元素 26 | byte[] resultByteArray = messageDigest.digest(); 27 | // 字符数组转换成字符串返回 28 | return byteArrayToHex(resultByteArray); 29 | } catch (NoSuchAlgorithmException e) { 30 | return null; 31 | } 32 | } 33 | 34 | private static String byteArrayToHex(byte[] byteArray) { 35 | 36 | // 首先初始化一个字符数组,用来存放每个16进制字符 37 | char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 38 | 'A', 'B', 'C', 'D', 'E', 'F' }; 39 | // new一个字符数组,这个就是用来组成结果字符串的(解释一下:一个byte是八位二进制,也就是2位十六进制字符(2的8次方等于16的2次方)) 40 | char[] resultCharArray = new char[byteArray.length * 2]; 41 | // 遍历字节数组,通过位运算(位运算效率高),转换成字符放到字符数组中去 42 | int index = 0; 43 | for (byte b : byteArray) { 44 | resultCharArray[index++] = hexDigits[b >>> 4 & 0xf]; 45 | resultCharArray[index++] = hexDigits[b & 0xf]; 46 | } 47 | // 字符数组组合成字符串返回 48 | return new String(resultCharArray); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/JUtils/excel/ExcelExportHelper.java: -------------------------------------------------------------------------------- 1 | package com.JUtils.excel; 2 | 3 | import java.beans.IntrospectionException; 4 | import java.beans.PropertyDescriptor; 5 | import java.io.File; 6 | import java.io.FileNotFoundException; 7 | import java.io.FileOutputStream; 8 | import java.io.IOException; 9 | import java.lang.reflect.Field; 10 | import java.lang.reflect.InvocationTargetException; 11 | import java.lang.reflect.Method; 12 | import java.text.SimpleDateFormat; 13 | import java.util.ArrayList; 14 | import java.util.Date; 15 | import java.util.Iterator; 16 | import java.util.List; 17 | import java.util.Random; 18 | import java.util.regex.Matcher; 19 | import java.util.regex.Pattern; 20 | import java.util.zip.ZipEntry; 21 | import java.util.zip.ZipOutputStream; 22 | 23 | import org.apache.poi.hssf.usermodel.HSSFCell; 24 | import org.apache.poi.hssf.usermodel.HSSFCellStyle; 25 | import org.apache.poi.hssf.usermodel.HSSFClientAnchor; 26 | import org.apache.poi.hssf.usermodel.HSSFFont; 27 | import org.apache.poi.hssf.usermodel.HSSFPatriarch; 28 | import org.apache.poi.hssf.usermodel.HSSFRichTextString; 29 | import org.apache.poi.hssf.usermodel.HSSFRow; 30 | import org.apache.poi.hssf.usermodel.HSSFSheet; 31 | import org.apache.poi.hssf.usermodel.HSSFWorkbook; 32 | import org.apache.poi.hssf.util.HSSFColor; 33 | 34 | /** 35 | * Excel 生成通用类,为了兼容,所有 Excel 统一生成 Excel2003 即:xx.xls 36 | * @Author : chenssy 37 | * @Date : 2014年6月15日 下午9:09:38 38 | */ 39 | public class ExcelExportHelper { 40 | 41 | /** 时间格式:默认为yyyy-MM-dd */ 42 | private String DATE_PATTERN = "yyyy-MM-dd"; 43 | 44 | /** 图片宽度,默认为:100 */ 45 | private int IMAGE_WIDTH = 30; 46 | 47 | /** 图片高度,默认为:50 */ 48 | private int IMAGE_HEIGHT = 5; 49 | 50 | /** 单元格的最大宽度 */ 51 | private int[] maxWidth; 52 | 53 | /** 54 | * 单页支持最多数据列:超过65534会出错 55 | * 若数据列多余65534则需要通过MORE_EXCEL_FLAG、MORE_SHEET_FLAG来区别生成多个Excel、还是sheet 56 | */ 57 | private int maxRowCount = 2500; 58 | 59 | /** 大量数据,多个Excel标识---0001 */ 60 | private String MORE_EXCEL_FLAG = "0001"; 61 | 62 | /** 大量数据,多个sheet标识---0001 */ 63 | private String MORE_SHEET_FLAG = "0002"; 64 | 65 | /** 66 | * 默认构造函数 67 | */ 68 | public ExcelExportHelper(){ 69 | } 70 | 71 | /** 72 | * @param datePattern 指定的时间格式 73 | */ 74 | public ExcelExportHelper(String datePattern){ 75 | this.DATE_PATTERN = datePattern; 76 | } 77 | 78 | /** 79 | * @param imageWidth 80 | * 指定图片的宽度 81 | * @param imageHeight 82 | * 指定图片的高度 83 | */ 84 | public ExcelExportHelper(int imageWidth,int imageHeight){ 85 | this.IMAGE_HEIGHT = imageHeight; 86 | this.IMAGE_WIDTH = imageWidth; 87 | } 88 | 89 | /** 90 | * @param datePatter 91 | * 指定时间格式 92 | * @param imageWidth 93 | * 指定图片的宽度 94 | * @param imageHeight 95 | * 指定图片的高度 96 | */ 97 | public ExcelExportHelper(String datePatter,int imageWidht,int imageHeight){ 98 | this.DATE_PATTERN = datePatter; 99 | this.IMAGE_HEIGHT = imageHeight; 100 | this.IMAGE_WIDTH = imageWidht; 101 | } 102 | 103 | /** 104 | * 通用方法,使用 java 反射机制,根据提供表头 header ,数据列 excelList 生成 Excel,如有图片请转换为byte[]
105 | * header、excelList规则如下:
106 | * header、excelList中的Bean必须对应(javaBean的属性顺序):如下
107 | * header:姓名、年龄、性别、班级
108 | * Bean:name、age、sex、class
109 | * 110 | * @author chenssy 111 | * @date 2014年6月15日 下午9:18:37 112 | * 113 | * @param header 114 | * 表格属性列名数组 115 | * @param excelList 116 | * 需要显示的数据集合,集合中一定要放置符合javabean风格的类的对象。此方法支持的 javabean 117 | * 属性的数据类型有基本数据类型及String,Date,byte[](图片数据) 118 | * @param sheetTitle 119 | * 表格标题名 120 | * @return 生成的HSSFWorkBook 121 | * @version 1.0 122 | */ 123 | public HSSFWorkbook exportExcel(String[] header,List excelList,String sheetTitle){ 124 | //生成一个Excel 125 | HSSFWorkbook book = new HSSFWorkbook(); 126 | //生成一个表格 127 | sheetTitle = getSheetTitle(sheetTitle); //判断、设置sheetTitle 128 | HSSFSheet sheet = book.createSheet(sheetTitle); 129 | 130 | //设置Excel里面数据 131 | setExcelContentData(book,sheet,header,excelList); 132 | 133 | System.out.println("——————————————————ExcelExportHelper:Excel生成成功..."); 134 | 135 | return book; 136 | } 137 | 138 | /** 139 | * 140 | * 通用方法,使用 java 反射机制,根据提供表头 header ,数据列 excelList 生成 Excel,如有图片请转换为byte[]
141 | * header、properties需要一一对应:
142 | * header = ["学号","年龄","性别","班级"] 143 | * properties = ["id","age","sex","class"],其对应的excelList中javaBean的属性值 144 | * 145 | * @author chenssy 146 | * @date 2014年6月19日 下午6:02:02 147 | * 148 | * @param header 149 | * Excel表头 150 | * @param properties 151 | * 表头对应javaBean中的属性 152 | * @param excelList 153 | * 需要显示的数据集合,集合中一定要放置符合javabean风格的类的对象。此方法支持的 154 | * javabean属性的数据类型有基本数据类型及String,Date,byte[](图片数据) 155 | * @param sheetTitle 156 | * 表格标题名 157 | * 158 | * @return 生成的HSSFWorkbook 159 | * @version 1.0 160 | */ 161 | public HSSFWorkbook exportExcel(String[] header,String[] properties,List excelList, 162 | String sheetTitle){ 163 | //生成一个Excel 164 | HSSFWorkbook book = new HSSFWorkbook(); 165 | // 生成一个表格 166 | sheetTitle = getSheetTitle(sheetTitle); // 判断、设置sheetTitle 167 | HSSFSheet sheet = book.createSheet(sheetTitle); 168 | 169 | // 设置Excel里面数据 170 | setExcelContentData(book, sheet, header, properties ,excelList); 171 | 172 | System.out.println("——————————————————ExcelExportHelper:Excel生成成功..."); 173 | 174 | return book; 175 | } 176 | 177 | /** 178 | * 通用方法,使用 java 反射机制,根据提供表头 header ,数据列 excelList 生成 Excel,并将Excel保存至某个路径下, 179 | * 如有图片请转换为byte[]
180 | * header、excelList规则如下:
181 | * header、excelList中的Bean必须一一对应(javaBean的属性顺序):如下
182 | * header:姓名、年龄、性别、班级
183 | * Bean:name、age、sex、class
184 | * 185 | * @author chenssy 186 | * @date 2014年6月17日 下午2:24:38 187 | * 188 | * @param header 189 | * 表格属性列名数组 190 | * @param excelList 191 | * 需要显示的数据集合,集合中一定要放置符合javabean风格的类的对象。此方法支持的 192 | * javabean属性的数据类型有基本数据类型及String,Date,byte[](图片数据) 193 | * @param sheetTitle 194 | * 表格标题名 195 | * @param filePath 196 | * Excel文件保存位置 197 | * @param fileName 198 | * Excel文件名 199 | * 200 | * @return 201 | * @version 1.0 202 | */ 203 | public void exportExcelAndSave(String[] header,List excelList,String sheetTitle, 204 | String filePath,String fileName){ 205 | //生成Excel 206 | HSSFWorkbook book = exportExcel(header, excelList, sheetTitle); 207 | 208 | //保存生成的Excel 209 | saveExcel(book,filePath,fileName); 210 | } 211 | 212 | /** 213 | * 通用方法,使用 java 反射机制,根据提供表头 header ,数据列 excelList 生成 Excel,并将Excel保存至某个路径下, 214 | * 如有图片请转换为byte[]
215 | * header、properties需要一一对应:
216 | * header = ["学号","年龄","性别","班级"]
217 | * properties = ["id","age","sex","class"],其对应的excelList中javaBean的属性值 218 | * 219 | * @author chenssy 220 | * @date 2014年6月19日 下午6:24:56 221 | * 222 | * @param header 223 | * 表格属性列名数组 224 | * @param properties 225 | * 表头对应javaBean中的属性 226 | * @param excelList 227 | * 需要显示的数据集合,集合中一定要放置符合javabean风格的类的对象。此方法支持的 228 | * javabean属性的数据类型有基本数据类型及String,Date,byte[](图片数据) 229 | * @param sheetTitle 230 | * 表格标题名 231 | * @param filePath 232 | * Excel文件保存位置 233 | * @param fileName 234 | * Excel文件名 235 | * @version 1.0 236 | */ 237 | public void exportExcelAndSave(String[] header,String[] properties,List excelList,String sheetTitle, 238 | String filePath,String fileName){ 239 | //生成Excel 240 | HSSFWorkbook book = exportExcel(header, properties,excelList, sheetTitle); 241 | //保存生成的Excel 242 | saveExcel(book,filePath,fileName); 243 | } 244 | 245 | /** 246 | * 通用方法,使用 java 反射机制,根据提供表头 header ,数据列 excelList 生成 Excel,并将 Excel 打包 zip 格式保存至某个路径下, 247 | * 如有图片请转换为byte[]
248 | * header、excelList规则如下:
249 | * header、excelList中的Bean必须一一对应(javaBean的属性顺序):如下
250 | * header:姓名、年龄、性别、班级
251 | * Bean:name、age、sex、class
252 | * 253 | * @author chenssy 254 | * @date 2014年6月18日 下午12:36:01 255 | * 256 | * @param header 257 | * 表格属性列名数组 258 | * @param excelList 259 | * 需要显示的数据集合,集合中一定要放置符合javabean风格的类的对象。此方法支持的 260 | * javabean属性的数据类型有基本数据类型及String,Date,byte[](图片数据) 261 | * @param sheetTitle 262 | * 表格标题名 263 | * @param filePath 264 | * zip文件保存位置 265 | * @param excelName 266 | * Excel名称 267 | * @param zipName 268 | * zip名称 269 | * 270 | * @version 1.0 271 | */ 272 | public void exportExcelAndZip(String[] header,List excelList,String sheetTitle, 273 | String filePath,String excelName,String zipName){ 274 | //生成Excel 275 | HSSFWorkbook book = exportExcel(header, excelList, sheetTitle); 276 | 277 | //将生成的Excel打包保存起来 278 | List books = new ArrayList(); 279 | books.add(book); 280 | zipExcelAndSave(books, filePath, zipName, excelName); 281 | } 282 | 283 | /** 284 | * 通用方法,使用 java 反射机制,根据提供表头 header ,数据列 excelList 生成 Excel,并将 Excel 打包 zip 格式保存至某个路径下, 285 | * 如有图片请转换为byte[]
286 | * header、properties需要一一对应:
287 | * header = ["学号","年龄","性别","班级"] 288 | * properties = ["id","age","sex","class"],其对应的excelList中javaBean的属性值 289 | * 290 | * @author chenssy 291 | * @date 2014年6月19日 下午6:33:04 292 | * 293 | * @param header 294 | * 表格属性列名数组 295 | * @param properties 296 | * 表头对应javaBean的属性 297 | * @param excelList 298 | * 需要显示的数据集合,集合中一定要放置符合javabean风格的类的对象。此方法支持的 299 | * javabean属性的数据类型有基本数据类型及String,Date,byte[](图片数据) 300 | * @param sheetTitle 301 | * 表格标题名 302 | * @param filePath 303 | * zip文件保存位置 304 | * @param excelName 305 | * Excel名称 306 | * @param zipName 307 | * zip名称 308 | * 309 | * @version 1.0 310 | */ 311 | public void exportExcelAndZip(String[] header,String[] properties,List excelList,String sheetTitle, 312 | String filePath,String excelName,String zipName){ 313 | //生成Excel 314 | HSSFWorkbook book = exportExcel(header, properties,excelList, sheetTitle); 315 | 316 | //将生成的Excel打包保存起来 317 | List books = new ArrayList(); 318 | books.add(book); 319 | zipExcelAndSave(books, filePath, zipName, excelName); 320 | } 321 | 322 | /** 323 | * 通用方法,使用 java 反射机制,根据提供表头 header ,数据列 excelList 生成 Excel,如有图片请转换为byte[]
324 | * 用于大数据量时使用,涉及到一个表只能有65536行,当数据量较大时会直接写入下一个表(excel、sheet) 325 | * header、excelList规则如下:
326 | * header、excelList中的Bean必须一一对应(javaBean的属性顺序):如下
327 | * header:姓名、年龄、性别、班级
328 | * Bean:name、age、sex、class
329 | * 330 | * @author chenssy 331 | * @date 2014年6月17日 下午9:53:15 332 | * 333 | * @param header 334 | * 表格属性列名数组 335 | * @param excelList 336 | * 需要显示的数据集合,集合中一定要放置符合javabean风格的类的对象。此方法支持的 337 | * javabean属性的数据类型有基本数据类型及String,Date,byte[](图片数据) 338 | * @param sheetTitle 339 | * 表格标题名 340 | * @param flag 341 | * 分页标识为。flag == 0001:生成多个Excel,flag == 0002:生成多个sheet 342 | * 343 | * @return List 344 | * @version 1.0 345 | */ 346 | public List exportExcelForBigData(String[] header,List excelList,String sheetTitle, 347 | String flag){ 348 | List list = new ArrayList<>(); //创建表数据结果集 349 | 350 | //判断需要生成几个Excel 351 | int num = excelList.size() % maxRowCount == 0 ? excelList.size() / maxRowCount : excelList.size() / maxRowCount + 1; 352 | 353 | HSSFWorkbook book = new HSSFWorkbook(); 354 | List newList = null; //新数据列表 355 | String newTitle = null; //新title 356 | for(int i = 0 ; i < num ; i++){ 357 | //计算新的数据列表 358 | int beginRowNum = maxRowCount * i; 359 | int endRowNum = maxRowCount * (i + 1) > excelList.size() ? excelList.size() : maxRowCount * (i + 1); 360 | newList = excelList.subList(beginRowNum, endRowNum); 361 | newTitle = getSheetTitle(sheetTitle) + "_" + i; 362 | if(MORE_EXCEL_FLAG.equals(flag)){ //如果是创建多个Excel 363 | book = exportExcel(header, newList, newTitle); 364 | list.add(book); 365 | } 366 | else if(MORE_SHEET_FLAG.equals(flag)){ //创建多sheet 367 | HSSFSheet sheet = book.createSheet(newTitle); 368 | setExcelContentData(book,sheet,header,newList); 369 | } 370 | } 371 | 372 | if(MORE_SHEET_FLAG.equals(flag)){ //创建多sheet 373 | list.add(book); 374 | } 375 | 376 | return list; 377 | } 378 | 379 | /** 380 | * 通用方法,使用 java 反射机制,根据提供表头 header ,数据列 excelList 生成 Excel,如有图片请转换为byte[]
381 | * 用于大数据量时使用,涉及到一个表只能有65536行,当数据量较大时会直接写入下一个表(excel、sheet) 382 | * header、properties需要一一对应:
383 | * header = ["学号","年龄","性别","班级"] 384 | * properties = ["id","age","sex","class"],其对应的excelList中javaBean的属性值 385 | * 386 | * @author chenssy 387 | * @date 2014年6月19日 下午6:41:23 388 | * 389 | * @param header 390 | * 表格属性列名数组 391 | * @param properties 392 | * 表头对应javaBean的属性 393 | * @param excelList 394 | * 需要显示的数据集合,集合中一定要放置符合javabean风格的类的对象。此方法支持的 395 | * javabean属性的数据类型有基本数据类型及String,Date,byte[](图片数据) 396 | * @param sheetTitle 397 | * 表格标题名 398 | * @param flag 399 | * 分页标识为。flag == 0001:生成多个Excel,flag == 0002:生成多个sheet 400 | * @return List 401 | * @version 1.0 402 | */ 403 | public List exportExcelForBigData(String[] header,String[] properties, 404 | List excelList,String sheetTitle, String flag){ 405 | List list = new ArrayList<>(); //创建表数据结果集 406 | // 判断需要生成几个Excel 407 | int num = excelList.size() % maxRowCount == 0 ? excelList.size() / maxRowCount : excelList.size() / maxRowCount + 1; 408 | 409 | HSSFWorkbook book = new HSSFWorkbook(); 410 | List newList = null; // 新数据列表 411 | String newTitle = null; // 新title 412 | for (int i = 0; i < num; i++) { 413 | // 计算新的数据列表 414 | int beginRowNum = maxRowCount * i; 415 | int endRowNum = maxRowCount * (i + 1) > excelList.size() ? excelList.size() : maxRowCount * (i + 1); 416 | newList = excelList.subList(beginRowNum, endRowNum); 417 | newTitle = getSheetTitle(sheetTitle) + "_" + i; 418 | if (MORE_EXCEL_FLAG.equals(flag)) { // 如果是创建多个Excel 419 | book = exportExcel(header,properties, newList, newTitle); 420 | list.add(book); 421 | } else if (MORE_SHEET_FLAG.equals(flag)) { // 创建多sheet 422 | HSSFSheet sheet = book.createSheet(newTitle); 423 | setExcelContentData(book, sheet, header, properties,newList); 424 | } 425 | } 426 | 427 | if (MORE_SHEET_FLAG.equals(flag)) { // 创建多sheet 428 | list.add(book); 429 | } 430 | return list; 431 | } 432 | 433 | 434 | /** 435 | * 通用方法,使用 java 反射机制,根据提供表头 header ,数据列 excelList 生成 Excel,并将Excel保存至某个路径下, 436 | * 如有图片请转换为byte[]
437 | * 用于大数据量时使用,涉及到一个表只能有65536行,当数据量较大时会直接写入下一个表(excel、sheet) 438 | * header、excelList规则如下:
439 | * header、excelList中的Bean必须一一对应(javaBean的属性顺序):如下
440 | * header:姓名、年龄、性别、班级
441 | * Bean:name、age、sex、class
442 | * 443 | * @author chenssy 444 | * @date 2014年6月17日 下午10:39:15 445 | * 446 | * @param header 447 | * 表格属性列名数组 448 | * @param excelList 449 | * 需要显示的数据集合,集合中一定要放置符合javabean风格的类的对象。此方法支持的 450 | * javabean属性的数据类型有基本数据类型及String,Date,byte[](图片数据) 451 | * @param sheetTitle 452 | * 表格标题名 453 | * @param flag 454 | * 分页标识为。flag == 0001:生成多个Excel,flag == 0002:生成多个sheet 455 | * @param filePath 456 | * 文件保存路径 457 | * @param fileName 458 | * 保存文件名 459 | * @return 460 | * @version 1.0 461 | */ 462 | public void exportExcelForBigDataAndSave(String[] header,List excelList,String sheetTitle, 463 | String flag,String filePath,String fileName){ 464 | //获取数据结果集 465 | List books = exportExcelForBigData(header, excelList, sheetTitle, flag); 466 | String _fileName = ""; 467 | for(int i = 0 ; i < books.size() ; i ++){ 468 | HSSFWorkbook book = books.get(i); 469 | _fileName = getFileName(fileName) + "_0" + i; 470 | //保存Excel文件 471 | saveExcel(book, filePath, _fileName); 472 | } 473 | } 474 | 475 | /** 476 | * 通用方法,使用 java 反射机制,根据提供表头 header ,数据列 excelList 生成 Excel,并将Excel保存至某个路径下, 477 | * 如有图片请转换为byte[]
478 | * 用于大数据量时使用,涉及到一个表只能有65536行,当数据量较大时会直接写入下一个表(excel、sheet) 479 | * header、properties需要一一对应:
480 | * header = ["学号","年龄","性别","班级"] 481 | * properties = ["id","age","sex","class"],其对应的excelList中javaBean的属性值 482 | * 483 | * @author chenssy 484 | * @date 2014年6月19日 下午8:22:25 485 | * 486 | * @param header 487 | * 表格属性列名数组 488 | * @param properties 489 | * 表头对应javaBean属性 490 | * @param excelList 491 | * 需要显示的数据集合,集合中一定要放置符合javabean风格的类的对象。此方法支持的 492 | * javabean属性的数据类型有基本数据类型及String,Date,byte[](图片数据) 493 | * @param sheetTitle 494 | * 表格标题名 495 | * @param flag 496 | * 分页标识为。flag == 0001:生成多个Excel,flag == 0002:生成多个sheet 497 | * @param filePath 498 | * 文件保存路径 499 | * @param fileName 500 | * 保存文件名 501 | * @version 1.0 502 | */ 503 | public void exportExcelForBigDataAndSave(String[] header,String[] properties,List excelList,String sheetTitle, 504 | String flag,String filePath,String fileName){ 505 | //获取数据结果集 506 | List books = exportExcelForBigData(header, properties,excelList, sheetTitle, flag); 507 | 508 | String _fileName = ""; 509 | for(int i = 0 ; i < books.size() ; i ++){ 510 | HSSFWorkbook book = books.get(i); 511 | _fileName = getFileName(fileName) + "_0" + i; 512 | //保存Excel文件 513 | saveExcel(book, filePath, _fileName); 514 | } 515 | } 516 | 517 | 518 | /** 519 | * 通用方法,使用 java 反射机制,根据提供表头 header ,数据列 excelList 生成 Excel,并将 Excel 打包成 ZIP 520 | * 保存至某个路径下,如有图片请转换为byte[]
521 | * 用于大数据量时使用,涉及到一个表只能有65536行,当数据量较大时会直接写入下一个表(excel、sheet) 522 | * header、excelList规则如下:
523 | * header、excelList中的Bean必须一一对应(javaBean的属性顺序):如下
524 | * header:姓名、年龄、性别、班级
525 | * Bean:name、age、sex、class
526 | * 527 | * @author chenssy 528 | * @date 2014年6月19日 下午10:39:15 529 | * 530 | * @param header 531 | * 表格属性列名数组 532 | * @param excelList 533 | * 需要显示的数据集合,集合中一定要放置符合javabean风格的类的对象。此方法支持的 534 | * javabean属性的数据类型有基本数据类型及String,Date,byte[](图片数据) 535 | * @param sheetTitle 536 | * 表格标题名 537 | * @param flag 538 | * 分页标识为。flag == 0001:生成多个Excel,flag == 0002:生成多个sheet 539 | * @param filePath 540 | * 文件保存路径 541 | * @param excelName 542 | * Excel文件名 543 | * @param zipName 544 | * zip文件名 545 | * @return 546 | * @version 1.0 547 | */ 548 | public void exportExcelForBigDataAndZipAndSave(String[] header,List excelList,String sheetTitle, 549 | String flag,String filePath,String excelName,String zipName){ 550 | //获取生成的Excel集合 551 | List books = exportExcelForBigData(header, excelList, sheetTitle, flag); 552 | 553 | //将生成的Excel打包并保存 554 | zipExcelAndSave(books, filePath, zipName, excelName); 555 | } 556 | 557 | /** 558 | * 通用方法,使用 java 反射机制,根据提供表头 header ,数据列 excelList 生成 Excel,并将 Excel 打包成 ZIP 559 | * 保存至某个路径下,如有图片请转换为byte[]
560 | * 用于大数据量时使用,涉及到一个表只能有65536行,当数据量较大时会直接写入下一个表(excel、sheet) 561 | * header、properties需要一一对应:
562 | * header = ["学号","年龄","性别","班级"] 563 | * properties = ["id","age","sex","class"],其对应的excelList中javaBean的属性值 564 | * 565 | * @author chenssy 566 | * @date 2014年6月19日 下午8:24:21 567 | * 568 | * @param header 569 | * 表格属性列名数组 570 | * @param properties 571 | * 表头对应javaBean属性 572 | * @param excelList 573 | * 需要显示的数据集合,集合中一定要放置符合javabean风格的类的对象。此方法支持的 574 | * javabean属性的数据类型有基本数据类型及String,Date,byte[](图片数据) 575 | * @param sheetTitle 576 | * 表格标题名 577 | * @param flag 578 | * 分页标识为。 flag == 0001:生成多个Excel,flag == 0002:生成多个sheet 579 | * @param filePath 580 | * 文件保存路径 581 | * @param excelName 582 | * Excel文件名 583 | * @param zipName 584 | * ZIP文件名 585 | * @version 1.0 586 | */ 587 | public void exportExcelForBigDataAndZipAndSave(String[] header,String[] properties,List excelList,String sheetTitle, 588 | String flag,String filePath,String excelName,String zipName){ 589 | //获取生成的Excel集合 590 | List books = exportExcelForBigData(header, properties,excelList, sheetTitle, flag); 591 | 592 | //将生成的Excel打包并保存 593 | zipExcelAndSave(books, filePath, zipName, excelName); 594 | } 595 | 596 | /** 597 | * 填充Excel数据内容 598 | * @author chenssy 599 | * @date 2014年6月17日 下午10:32:34 600 | * @param book Excel 601 | * @param sheet sheet 602 | * @param header Excel头部title 603 | * @param excelList Excel数据列 604 | * @version 1.0 605 | */ 606 | @SuppressWarnings({ "rawtypes", "unchecked", "deprecation" }) 607 | private void setExcelContentData(HSSFWorkbook book,HSSFSheet sheet,String[] header,List excelList) { 608 | //设置列头样式(居中、变粗、蓝色) 609 | HSSFCellStyle headerStyle = book.createCellStyle(); 610 | setHeaderStyle(headerStyle, book); 611 | 612 | // 设置单元格样式 613 | HSSFCellStyle cellStyle = book.createCellStyle(); 614 | setCellStyle(cellStyle, book); 615 | 616 | // 创建头部 617 | HSSFRow row = createHeader(sheet, headerStyle, header); 618 | 619 | // 画图的顶级管理器,一个sheet只能获取一个(一定要注意这点) 620 | HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); 621 | 622 | 623 | int index = 0; 624 | /* 避免在迭代过程中产生的新对象太多,这里讲循环内部变量全部移出来 */ 625 | Object t = null; 626 | HSSFCell cell = null; 627 | Field field = null; 628 | String fieldName = null; 629 | String getMethodName = null; 630 | Class tCls = null; 631 | Method getMethod = null; 632 | Object value = null; 633 | // 遍历集合数据,产生数据行 634 | Iterator it = excelList.iterator(); 635 | maxWidth = new int[header.length]; //初始化单元格宽度 636 | while (it.hasNext()) { 637 | index++; 638 | row = sheet.createRow(index); 639 | // 设置数据列 640 | t = it.next(); 641 | // 利用反射,根据javabean属性的先后顺序,动态调用getXxx()方法得到属性值 642 | Field[] fields = t.getClass().getDeclaredFields(); 643 | for (short i = 0; i < fields.length; i++) { 644 | cell = row.createCell(i); 645 | cell.setCellStyle(cellStyle); 646 | field = fields[i]; 647 | fieldName = field.getName(); 648 | getMethodName = "get"+ fieldName.substring(0, 1).toUpperCase()+ fieldName.substring(1); //构建getter方法 649 | try { 650 | tCls = t.getClass(); 651 | getMethod = tCls.getMethod(getMethodName,new Class[] {}); 652 | value = (Object) getMethod.invoke(t, new Object[] {}); 653 | // 将value设置当单元格指定位置 654 | setCellData(row, index, i, value, cell, sheet, patriarch, book); 655 | } catch (NoSuchMethodException e) { 656 | e.printStackTrace(); 657 | System.out.println("——————————————————创建Excel数据列表时出错。method:setDataRow,message:"+e.getMessage()); 658 | } catch (SecurityException e) { 659 | e.printStackTrace(); 660 | System.out.println("——————————————————创建Excel数据列表时出错。method:setDataRow,message:"+e.getMessage()); 661 | } catch (IllegalAccessException e) { 662 | e.printStackTrace(); 663 | System.out.println("——————————————————创建Excel数据列表时出错。method:setDataRow,message:"+e.getMessage()); 664 | } catch (IllegalArgumentException e) { 665 | e.printStackTrace(); 666 | System.out.println("——————————————————创建Excel数据列表时出错。method:setDataRow,message:"+e.getMessage()); 667 | } catch (InvocationTargetException e) { 668 | e.printStackTrace(); 669 | System.out.println("——————————————————创建Excel数据列表时出错。method:setDataRow,message:"+e.getMessage()); 670 | } 671 | } 672 | } 673 | 674 | System.out.println("-------------------------填充Excel数据成功.........."); 675 | } 676 | 677 | /** 678 | * 填充Excel内容 679 | * @author chenssy 680 | * @date 2014年6月19日 下午6:00:35 681 | * @param book 682 | * @param sheet 683 | * @param header 684 | * @param properties 685 | * @param excelList 686 | * @version 1.0 687 | */ 688 | @SuppressWarnings("rawtypes") 689 | private void setExcelContentData(HSSFWorkbook book, HSSFSheet sheet, String[] header, String[] properties, 690 | List excelList) { 691 | //设置列头样式(居中、变粗、蓝色) 692 | HSSFCellStyle headerStyle = book.createCellStyle(); 693 | setHeaderStyle(headerStyle, book); 694 | 695 | // 设置单元格样式 696 | HSSFCellStyle cellStyle = book.createCellStyle(); 697 | setCellStyle(cellStyle, book); 698 | 699 | // 创建头部 700 | HSSFRow row = createHeader(sheet, headerStyle, header); 701 | 702 | // 画图的顶级管理器,一个sheet只能获取一个(一定要注意这点) 703 | HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); 704 | 705 | /* 为了避免迭代过程中产生过多的新对象,这里将循环内部变量全部移出来 */ 706 | int index = 0; 707 | Object t = null; 708 | HSSFCell cell = null; 709 | Object o = null; 710 | Class clazz = null; 711 | PropertyDescriptor pd = null; 712 | Method getMethod = null; 713 | // 遍历集合数据,产生数据行 714 | Iterator it = excelList.iterator(); 715 | maxWidth = new int[header.length]; //初始化单元格宽度 716 | while (it.hasNext()) { 717 | index++; 718 | row = sheet.createRow(index); 719 | // 设置数据列 720 | t = it.next(); 721 | for(int i = 0 ; i < header.length ; i++){ 722 | cell = row.createCell(i); 723 | cell.setCellStyle(cellStyle); 724 | o = null; //每一个单元格都需要将O设置为null 725 | try { 726 | clazz = t.getClass(); 727 | pd = new PropertyDescriptor(properties[i],clazz); 728 | getMethod = pd.getReadMethod(); // 获得get方法 729 | if (pd != null) { 730 | o = getMethod.invoke(t); //执行get方法返回一个Object 731 | } 732 | setCellData(row, index, i, o, cell, sheet, patriarch, book); 733 | } catch (IntrospectionException e) { 734 | e.printStackTrace(); 735 | System.out.println("——————————————————创建Excel数据列表时出错。method:setDataRow,message:"+e.getMessage()); 736 | } catch (IllegalAccessException e) { 737 | e.printStackTrace(); 738 | System.out.println("——————————————————创建Excel数据列表时出错。method:setDataRow,message:"+e.getMessage()); 739 | } catch (IllegalArgumentException e) { 740 | e.printStackTrace(); 741 | System.out.println("——————————————————创建Excel数据列表时出错。method:setDataRow,message:"+e.getMessage()); 742 | } catch (InvocationTargetException e) { 743 | e.printStackTrace(); 744 | System.out.println("——————————————————创建Excel数据列表时出错。method:setDataRow,message:"+e.getMessage()); 745 | } 746 | } 747 | } 748 | 749 | System.out.println("——————————————————填充Excel数据成功.........."); 750 | } 751 | 752 | /** 753 | * 设置sheet的title,若为空则为yyyyMMddHH24mmss 754 | * @author chenssy 755 | * @date 2014年6月16日 下午1:46:06 756 | * @param sheetTitle 757 | * @return 758 | * @version 1.0 759 | */ 760 | private String getSheetTitle(String sheetTitle) { 761 | String title = null; 762 | if(sheetTitle != null && !"".equals(sheetTitle)){ 763 | title = sheetTitle; 764 | } 765 | else{ 766 | Date date = new Date(); 767 | SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHH24mmss"); 768 | title = sdf.format(date); 769 | } 770 | return title; 771 | } 772 | 773 | /** 774 | * 设置Excel图片的格式:字体居中、变粗、蓝色、12号 775 | * @author chenssy 776 | * @date 2014年6月16日 下午8:46:49 777 | * @param headerStyle 778 | * 头部样式 779 | * @param book 780 | * 生产的excel book HSSFWorkbook对象 781 | * @version 1.0 782 | */ 783 | private void setHeaderStyle(HSSFCellStyle headerStyle,HSSFWorkbook book) { 784 | headerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); //水平居中 785 | headerStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//垂直居中 786 | //设置字体 787 | HSSFFont font = book.createFont(); 788 | font.setFontHeightInPoints((short) 12); //字号:12号 789 | font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); //变粗 790 | font.setColor(HSSFColor.BLUE.index); //蓝色 791 | 792 | headerStyle.setFont(font); 793 | } 794 | 795 | /** 796 | * 设置单元格样式 797 | * @author chenssy 798 | * @date 2014年6月17日 上午11:00:53 799 | * @param cellStyle 800 | * 单元格样式 801 | * @param book 802 | * book HSSFWorkbook对象 803 | * @version 1.0 804 | */ 805 | private void setCellStyle(HSSFCellStyle cellStyle, HSSFWorkbook book) { 806 | cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); //水平居中 807 | cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//垂直居中 808 | 809 | HSSFFont font = book.createFont(); 810 | font.setFontHeightInPoints((short)12); 811 | 812 | cellStyle.setFont(font); 813 | } 814 | 815 | /** 816 | * 根据头部样式、头部数据创建Excel头部 817 | * @author chenssy 818 | * @date 2014年6月17日 上午11:37:28 819 | * @param sheet 820 | * sheet 821 | * @param headerStyle 822 | * 头部样式 823 | * @param header 824 | * 头部数据 825 | * @return 设置完成的头部Row 826 | * @version 1.0 827 | */ 828 | private HSSFRow createHeader(HSSFSheet sheet,HSSFCellStyle headerStyle, 829 | String[] header) { 830 | HSSFRow headRow = sheet.createRow(0); 831 | headRow.setHeightInPoints((short)(20)); //设置头部高度 832 | //添加数据 833 | HSSFCell cell = null; 834 | for(int i = 0 ; i < header.length ; i++){ 835 | cell = headRow.createCell(i); 836 | cell.setCellStyle(headerStyle); 837 | HSSFRichTextString text = new HSSFRichTextString(header[i]); 838 | cell.setCellValue(text); 839 | } 840 | 841 | return headRow; 842 | } 843 | 844 | /** 845 | * 设置单元格数据 846 | * @author chenssy 847 | * @date 2014年6月17日 上午11:48:14 848 | * @param row 849 | * 指定行 850 | * @param index 851 | * @param i 852 | * 行数 853 | * @param value 854 | * 单元格值 cellValue 855 | * @param cell 856 | * 单元格 HSSFCell对象 857 | * @param sheet 858 | * sheet HSSFSheet对象 859 | * @param patriarch 860 | * 顶级画板 用于实现突破 861 | * @param book 862 | * Excel HSSFWorkbook对象 863 | * @version 1.0 864 | */ 865 | private void setCellData(HSSFRow row, int index ,int i ,Object value,HSSFCell cell,HSSFSheet sheet,HSSFPatriarch patriarch,HSSFWorkbook book) { 866 | String textValue = null; 867 | if (value instanceof Date) { //为日期设置时间格式 868 | Date date = (Date) value; 869 | SimpleDateFormat sdf = new SimpleDateFormat(DATE_PATTERN); 870 | textValue = sdf.format(date); 871 | } 872 | if(value instanceof byte[]){ //byte为图片 873 | //设置图片单元格宽度、高度 874 | row.setHeightInPoints((short)(IMAGE_HEIGHT * 10)); 875 | sheet.setColumnWidth(i, IMAGE_WIDTH * 256); 876 | HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 1023, 255,(short) i, index, (short) i, index); 877 | anchor.setAnchorType(3); 878 | //插入图片 879 | byte[] bsValue = (byte[]) value; 880 | patriarch.createPicture(anchor, book.addPicture(bsValue, HSSFWorkbook.PICTURE_TYPE_JPEG)); 881 | } 882 | else{ //其余全部当做字符处理 883 | if(value != null){ 884 | textValue = String.valueOf(value); 885 | } 886 | else{ 887 | textValue = ""; 888 | } 889 | } 890 | // 如果不是图片数据,就利用正则表达式判断textValue是否全部由数字组成 891 | if (textValue != null) { 892 | Pattern p = Pattern.compile("^//d+(//.//d+)?$"); 893 | Matcher matcher = p.matcher(textValue); 894 | 895 | //设置单元格宽度,是文字能够全部显示 896 | setCellMaxWidth(textValue,i); 897 | sheet.setColumnWidth(i, maxWidth[i]); //设置单元格宽度 898 | row.setHeightInPoints((short)(20)); //设置单元格高度 899 | if (matcher.matches()) { 900 | // 是数字当作double处理 901 | cell.setCellValue(Double.parseDouble(textValue)); 902 | } else { 903 | cell.setCellValue(textValue); 904 | } 905 | } 906 | } 907 | 908 | /** 909 | * 获取文件名,若为空,则规则为:yyyyMMddHH24mmss+6位随机数 910 | * @author chenssy 911 | * @date 2014年6月17日 下午5:44:27 912 | * @param fileName 913 | * 文件名 914 | * @return 915 | * @version 1.0 916 | */ 917 | private String getFileName(String fileName) { 918 | if(fileName == null || "".equals(fileName)){ 919 | //日期 920 | Date date = new Date(); 921 | SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHH24mmss"); 922 | //随机数 923 | Random random = new Random(); 924 | fileName = sdf.format(date) + String.valueOf(Math.abs(random.nextInt() * 1000000)); 925 | } 926 | return fileName; 927 | } 928 | 929 | /** 930 | * 根据字数来获取单元格大小,并更新当前列的最大宽度 931 | * @author chenssy 932 | * @date 2014年6月17日 下午7:35:52 933 | * @param textValue 934 | * @param 指定列 935 | * @return 936 | * @version 1.0 937 | */ 938 | private void setCellMaxWidth(String textValue,int i ) { 939 | int size = textValue.length(); 940 | int width = (size + 6) * 256; 941 | if(maxWidth[i] <= width){ 942 | maxWidth[i] = width; 943 | } 944 | } 945 | 946 | /** 947 | * 将生成的Excel保存到指定路径下 948 | * @author chenssy 949 | * @date 2014年6月19日 下午6:10:17 950 | * @param book 951 | * 生成的Excel HSSFWorkbook对象 952 | * @param filePath 953 | * 需要保存的路劲 954 | * @param fileName 955 | * Excel文件名 956 | * @version 1.0 957 | */ 958 | private void saveExcel(HSSFWorkbook book, String filePath, String fileName) { 959 | //检测保存路劲是否存在,不存在则新建 960 | checkFilePathIsExist(filePath); 961 | //将Excel保存至指定目录下 962 | fileName = getFileName(fileName); 963 | FileOutputStream out = null; 964 | try { 965 | out = new FileOutputStream(filePath + "\\" + fileName + ".xls"); 966 | book.write(out); 967 | System.out.println("——————————————————保存Excel文件成功,保存路径:" + filePath + "\\" + fileName + ".xls"); 968 | } catch (Exception e) { 969 | e.printStackTrace(); 970 | System.out.println("——————————————————保存Excel文件失败。exportExcelForListAndSave,message:"+e.getMessage()); 971 | }finally{ 972 | if(out != null){ 973 | try { 974 | out.close(); 975 | } catch (IOException e) { 976 | e.printStackTrace(); 977 | } 978 | } 979 | } 980 | } 981 | 982 | /** 983 | * 将生成的Excel打包并保存到指定路径下 984 | * @author chenssy 985 | * @date 2014年6月19日 下午6:18:09 986 | * @param book 987 | * 生成的Excel HSSFWorkbook list集合 988 | * @param filePath 989 | * 保存路劲 990 | * @param zipName 991 | * zip 文件名 992 | * @param excelName 993 | * Excel文件名 994 | * @version 1.0 995 | */ 996 | private void zipExcelAndSave(List books,String filePath,String zipName,String excelName){ 997 | //检测保存路径是否存在,若不存在则新建 998 | checkFilePathIsExist(filePath); 999 | 1000 | zipName = getFileName(zipName); 1001 | excelName = getFileName(excelName); 1002 | 1003 | //将Excel打包并保存至指定目录下 1004 | FileOutputStream out = null; 1005 | ZipOutputStream zip = null; 1006 | try { 1007 | out = new FileOutputStream(filePath + "\\" + zipName + ".zip"); 1008 | zip = new ZipOutputStream(out); 1009 | HSSFWorkbook book = null; 1010 | String _excelName = ""; 1011 | for (int i = 0; i < books.size(); i++) { 1012 | book = books.get(i); 1013 | _excelName = getFileName(excelName) + "_0" + i; 1014 | ZipEntry entry = new ZipEntry(_excelName + ".xls"); 1015 | zip.putNextEntry(entry); 1016 | book.write(zip); 1017 | } 1018 | System.out.println("——————————————————保存Excel文件成功,保存路径:" + filePath + "\\" + zipName + ".xls"); 1019 | } catch (FileNotFoundException e) { 1020 | e.printStackTrace(); 1021 | System.out.println("——————————————————保存Excel文件失败。method:exportExcelForBigDataAndSave,message:" + e.getMessage()); 1022 | } catch (IOException e) { 1023 | e.printStackTrace(); 1024 | System.out.println("——————————————————保存Excel文件失败。method:exportExcelForBigDataAndSave,message:" + e.getMessage()); 1025 | } finally { 1026 | if (zip != null) { 1027 | try { 1028 | zip.flush(); 1029 | zip.close(); 1030 | } catch (IOException e) { 1031 | e.printStackTrace(); 1032 | } 1033 | } 1034 | 1035 | if (out != null) { 1036 | try { 1037 | out.flush(); 1038 | out.close(); 1039 | } catch (IOException e) { 1040 | e.printStackTrace(); 1041 | } 1042 | } 1043 | } 1044 | } 1045 | 1046 | /** 1047 | * 检测保存路径是否存在,不存在则新建 1048 | * @author chenssy 1049 | * @date 2014年6月18日 下午1:05:17 1050 | * @param filePath 1051 | * 文件路径 1052 | * @version 1.0 1053 | */ 1054 | private void checkFilePathIsExist(String filePath) { 1055 | File file = new File(filePath); 1056 | 1057 | if(!file.exists()){ 1058 | file.mkdirs(); 1059 | } 1060 | } 1061 | } 1062 | -------------------------------------------------------------------------------- /src/main/java/com/JUtils/excel/ExcelReadHelper.java: -------------------------------------------------------------------------------- 1 | package com.JUtils.excel; 2 | 3 | import java.io.File; 4 | import java.io.FileInputStream; 5 | import java.lang.reflect.Field; 6 | import java.lang.reflect.Method; 7 | import java.lang.reflect.Modifier; 8 | import java.math.BigDecimal; 9 | import java.util.ArrayList; 10 | import java.util.HashMap; 11 | import java.util.List; 12 | import java.util.Map; 13 | 14 | import org.apache.poi.hssf.usermodel.HSSFWorkbook; 15 | import org.apache.poi.ss.usermodel.Cell; 16 | import org.apache.poi.ss.usermodel.Row; 17 | import org.apache.poi.ss.usermodel.Sheet; 18 | import org.apache.poi.ss.usermodel.Workbook; 19 | import org.apache.poi.ss.util.NumberToTextConverter; 20 | import org.apache.poi.xssf.usermodel.XSSFWorkbook; 21 | 22 | import com.JUtils.date.DateUtils; 23 | import com.JUtils.date.DateFormatUtils; 24 | 25 | /** 26 | * 解析Excel,支持2003、2007 27 | * 28 | * @Author:chenssy 29 | * @date:2014年8月3日 30 | */ 31 | public class ExcelReadHelper { 32 | 33 | /** 34 | * 解析Excel 支持2003、2007
35 | * 利用反射技术完成propertis到obj对象的映射,并将相对应的值利用相对应setter方法设置到obj对象中最后add到list集合中
36 | * properties、obj需要符合如下规则:
37 | * 1、obj对象必须存在默认构造函数,且属性需存在setter方法
38 | * 2、properties中的值必须是在obj中存在的属性,且obj中必须存在这些属性的setter方法。
39 | * 3、properties中值得顺序要与Excel中列相相应,否则值会设置错:
40 | *         excel:编号 姓名 年龄 性别
41 | * properties:id name age sex
42 | * 43 | * @autor:chenssy 44 | * @date:2014年8月9日 45 | * 46 | * @param file 47 | * 待解析的Excel文件 48 | * @param properties 49 | * 与Excel相对应的属性 50 | * @param obj 51 | * 反射对象的Class 52 | * @return 53 | * @throws Exception 54 | */ 55 | @SuppressWarnings("rawtypes") 56 | public static List excelRead(File file,String[] properties,Class obj) throws Exception{ 57 | Workbook book = null; 58 | try { 59 | book = new XSSFWorkbook(new FileInputStream(file)); //解析2003 60 | } catch (Exception e) { 61 | book = new HSSFWorkbook(new FileInputStream(file)); //解析2007 62 | } 63 | 64 | return getExcelContent(book,properties,obj); 65 | } 66 | 67 | /** 68 | * 解析Excel 支持2003、2007
69 | * 利用反射技术完成propertis到obj对象的映射,并将相对应的值利用相对应setter方法设置到obj对象中最后add到list集合中
70 | * properties、obj需要符合如下规则:
71 | * 1、obj对象必须存在默认构造函数,且属性需存在setter方法
72 | * 2、properties中的值必须是在obj中存在的属性,且obj中必须存在这些属性的setter方法。
73 | * 3、properties中值得顺序要与Excel中列相相应,否则值会设置错:
74 | *         excel:编号 姓名 年龄 性别
75 | * properties:id name age sex
76 | * 77 | * @autor:chenssy 78 | * @date:2014年8月9日 79 | * 80 | * @param file 81 | * 待解析的Excel文件的路径 82 | * @param properties 83 | * 与Excel相对应的属性 84 | * @param obj 85 | * 反射对象的Class 86 | * @return 87 | * @throws Exception 88 | */ 89 | @SuppressWarnings("rawtypes") 90 | public static List excelRead(String filePath,String[] properties,Class obj) throws Exception{ 91 | File file = new File(filePath); 92 | if(!file.exists()){ 93 | throw new Exception("指定的文件不存在"); 94 | } 95 | return excelRead(file, properties, obj); 96 | } 97 | 98 | /** 99 | * 根据params、object解析Excel,并且构建list集合 100 | * @autor:chenssy 101 | * @date:2014年8月9日 102 | * 103 | * @param book 104 | * WorkBook对象,他代表了待将解析的Excel文件 105 | * @param properties 106 | * 需要参考Object的属性 107 | * @param object 108 | * 构建的Object对象,每一个row都相当于一个object对象 109 | * @return 110 | * @throws Exception 111 | */ 112 | @SuppressWarnings("rawtypes") 113 | private static List getExcelContent(Workbook book, String[] properties, 114 | Class obj) throws Exception { 115 | List resultList = new ArrayList(); //初始化结果解 116 | Map methodMap = getObjectSetterMethod(obj); 117 | Map fieldMap = getObjectField(obj); 118 | for(int numSheet = 0 ; numSheet < book.getNumberOfSheets(); numSheet++){ 119 | Sheet sheet = book.getSheetAt(numSheet); 120 | if(sheet == null){ //谨防中间空一行 121 | continue; 122 | } 123 | 124 | for(int numRow = 1 ; numRow < sheet.getLastRowNum() ; numRow++){ //一个row就相当于一个Object 125 | Row row = sheet.getRow(numRow); 126 | if(row == null){ 127 | continue; 128 | } 129 | resultList.add(getObject(row,properties,methodMap,fieldMap,obj)); 130 | } 131 | } 132 | return resultList; 133 | } 134 | 135 | /** 136 | * 获取row的数据,利用反射机制构建Object对象 137 | * @autor:chenssy 138 | * @date:2014年8月9日 139 | * 140 | * @param row 141 | * row对象 142 | * @param properties 143 | * Object参考的属性 144 | * @param methodMap 145 | * object对象的setter方法映射 146 | * @param fieldMap 147 | * object对象的属性映射 148 | * @return 149 | * @throws Exception 150 | */ 151 | @SuppressWarnings("rawtypes") 152 | private static Object getObject(Row row, String[] properties, 153 | Map methodMap,Map fieldMap,Class obj) throws Exception { 154 | Object object = obj.newInstance(); 155 | for(int numCell = 0 ; numCell < row.getLastCellNum() ; numCell++){ 156 | Cell cell = row.getCell(numCell); 157 | if(cell == null){ 158 | continue; 159 | } 160 | String cellValue = getValue(cell); 161 | String property = properties[numCell].toLowerCase(); 162 | Field field = fieldMap.get(property); //该property在object对象中对应的属性 163 | Method method = methodMap.get(property); //该property在object对象中对应的setter方法 164 | setObjectPropertyValue(object,field,method,cellValue); 165 | } 166 | return object; 167 | } 168 | 169 | /** 170 | * 根据指定属性的的setter方法给object对象设置值 171 | * @autor:chenssy 172 | * @date:2014年8月10日 173 | * 174 | * @param obj 175 | * object对象 176 | * @param field 177 | * object对象的属性 178 | * @param method 179 | * object对象属性的相对应的方法 180 | * @param value 181 | * 需要设置的值 182 | * @throws Exception 183 | */ 184 | private static void setObjectPropertyValue(Object obj, Field field, 185 | Method method, String value) throws Exception { 186 | Object[] oo = new Object[1]; 187 | 188 | String type = field.getType().getName(); 189 | if ("java.lang.String".equals(type) || "String".equals(type)) { 190 | oo[0] = value; 191 | } else if ("java.lang.Integer".equals(type) || "java.lang.int".equals(type) || "Integer".equals(type) || "int".equals(type)) { 192 | if (value.length() > 0) 193 | oo[0] = Integer.valueOf(value); 194 | } else if ("java.lang.Float".equals(type) || "java.lang.float".equals(type) || "Float".equals(type) || "float".equals(type)) { 195 | if (value.length() > 0) 196 | oo[0] = Float.valueOf(value); 197 | } else if ("java.lang.Double".equals(type) || "java.lang.double".equals(type) || "Double".equals(type) || "double".equals(type)) { 198 | if (value.length() > 0) 199 | oo[0] = Double.valueOf(value); 200 | } else if ("java.math.BigDecimal".equals(type) || "BigDecimal".equals(type)) { 201 | if (value.length() > 0) 202 | oo[0] = new BigDecimal(value); 203 | } else if ("java.util.Date".equals(type) || "Date".equals(type)) { 204 | if (value.length() > 0){//当长度为19(yyyy-MM-dd HH24:mm:ss)或者为14(yyyyMMddHH24mmss)时Date格式转换为yyyyMMddHH24mmss 205 | if(value.length() == 19 || value.length() == 14){ 206 | oo[0] = DateUtils.string2Date(value, "yyyyMMddHH24mmss"); 207 | } 208 | else{ //其余全部转换为yyyyMMdd格式 209 | oo[0] = DateUtils.string2Date(value, "yyyyMMdd"); 210 | } 211 | } 212 | } else if ("java.sql.Timestamp".equals(type)) { 213 | if (value.length() > 0) 214 | oo[0] = DateFormatUtils.formatDate(value, "yyyyMMddHH24mmss"); 215 | } else if ("java.lang.Boolean".equals(type) || "Boolean".equals(type)) { 216 | if (value.length() > 0) 217 | oo[0] = Boolean.valueOf(value); 218 | } else if ("java.lang.Long".equals(type) || "java.lang.long".equals(type) || "Long".equals(type) || "long".equals(type)) { 219 | if (value.length() > 0) 220 | oo[0] = Long.valueOf(value); 221 | } 222 | try { 223 | method.invoke(obj, oo); 224 | } catch (Exception e) { 225 | e.printStackTrace(); 226 | throw e; 227 | } 228 | } 229 | 230 | @SuppressWarnings("static-access") 231 | private static String getValue(Cell cell) { 232 | if (cell.getCellType() == cell.CELL_TYPE_BOOLEAN) { 233 | return String.valueOf(cell.getBooleanCellValue()); 234 | } else if (cell.getCellType() == cell.CELL_TYPE_NUMERIC) { 235 | return NumberToTextConverter.toText(cell.getNumericCellValue()); 236 | } else { 237 | return String.valueOf(cell.getStringCellValue()); 238 | } 239 | } 240 | 241 | /** 242 | * 获取object对象所有属性的Setter方法,并构建map对象,结构为Map<'field','method'> 243 | * @autor:chenssy 244 | * @date:2014年8月9日 245 | * 246 | * @param object 247 | * object对象 248 | * @return 249 | */ 250 | @SuppressWarnings("rawtypes") 251 | private static Map getObjectSetterMethod(Class object) { 252 | Field[] fields = object.getDeclaredFields(); //获取object对象的所有属性 253 | Method[] methods = object.getDeclaredMethods(); //获取object对象的所有方法 254 | Map methodMap = new HashMap(); 255 | for(Field field : fields){ 256 | String attri = field.getName(); 257 | for(Method method : methods){ 258 | String meth = method.getName(); 259 | //匹配set方法 260 | if(meth != null && "set".equals(meth.substring(0, 3)) && 261 | Modifier.isPublic(method.getModifiers()) && 262 | ("set"+Character.toUpperCase(attri.charAt(0))+attri.substring(1)).equals(meth)){ 263 | methodMap.put(attri.toLowerCase(), method); //将匹配的setter方法加入map对象中 264 | break; 265 | } 266 | } 267 | } 268 | 269 | return methodMap; 270 | } 271 | 272 | /** 273 | * 获取object对象的所有属性,并构建map对象,对象结果为Map<'field','field'> 274 | * @autor:chenssy 275 | * @date:2014年8月10日 276 | * 277 | * @param object 278 | * object对象 279 | * @return 280 | */ 281 | @SuppressWarnings("rawtypes") 282 | private static Map getObjectField(Class object) { 283 | Field[] fields = object.getDeclaredFields(); //获取object对象的所有属性 284 | Map fieldMap = new HashMap(); 285 | for(Field field : fields){ 286 | String attri = field.getName(); 287 | fieldMap.put(attri.toLowerCase(), field); 288 | } 289 | return fieldMap; 290 | } 291 | } 292 | -------------------------------------------------------------------------------- /src/main/java/com/JUtils/file/FileUtils.java: -------------------------------------------------------------------------------- 1 | package com.JUtils.file; 2 | 3 | import java.io.File; 4 | import java.io.FileInputStream; 5 | import java.io.FileOutputStream; 6 | import java.io.IOException; 7 | import java.io.InputStream; 8 | import java.io.OutputStream; 9 | import java.math.BigInteger; 10 | import java.security.MessageDigest; 11 | 12 | import com.JUtils.date.DateUtils; 13 | import com.JUtils.math.RandomUtils; 14 | 15 | /** 16 | * @desc:文件工具类 17 | * 18 | * @Author:chenssy 19 | * @date:2014年8月7日 20 | */ 21 | public class FileUtils { 22 | private static final String FOLDER_SEPARATOR = "/"; 23 | private static final char EXTENSION_SEPARATOR = '.'; 24 | 25 | /** 26 | * @desc:判断指定路径是否存在,如果不存在,根据参数决定是否新建 27 | * @autor:chenssy 28 | * @date:2014年8月7日 29 | * 30 | * @param filePath 31 | * 指定的文件路径 32 | * @param isNew 33 | * true:新建、false:不新建 34 | * @return 存在返回TRUE,不存在返回FALSE 35 | */ 36 | public static boolean isExist(String filePath,boolean isNew){ 37 | File file = new File(filePath); 38 | if(!file.exists() && isNew){ 39 | return file.mkdirs(); //新建文件路径 40 | } 41 | return false; 42 | } 43 | 44 | /** 45 | * 获取文件名,构建结构为 prefix + yyyyMMddHH24mmss + 10位随机数 + suffix + .type 46 | * @autor:chenssy 47 | * @date:2014年8月11日 48 | * 49 | * @param type 50 | * 文件类型 51 | * @param prefix 52 | * 前缀 53 | * @param suffix 54 | * 后缀 55 | * @return 56 | */ 57 | public static String getFileName(String type,String prefix,String suffix){ 58 | String date = DateUtils.getCurrentTime("yyyyMMddHH24mmss"); //当前时间 59 | String random = RandomUtils.generateNumberString(10); //10位随机数 60 | 61 | //返回文件名 62 | return prefix + date + random + suffix + "." + type; 63 | } 64 | 65 | /** 66 | * 获取文件名,文件名构成:当前时间 + 10位随机数 + .type 67 | * @autor:chenssy 68 | * @date:2014年8月11日 69 | * 70 | * @param type 71 | * 文件类型 72 | * @return 73 | */ 74 | public static String getFileName(String type){ 75 | return getFileName(type, "", ""); 76 | } 77 | 78 | /** 79 | * 获取文件名,文件构成:当前时间 + 10位随机数 80 | * @autor:chenssy 81 | * @date:2014年8月11日 82 | * 83 | * @return 84 | */ 85 | public static String getFileName(){ 86 | String date = DateUtils.getCurrentTime("yyyyMMddHH24mmss"); //当前时间 87 | String random = RandomUtils.generateNumberString(10); //10位随机数 88 | 89 | //返回文件名 90 | return date + random; 91 | } 92 | 93 | /** 94 | * 获取指定文件的大小 95 | * 96 | * @param file 97 | * @return 98 | * @throws Exception 99 | * 100 | * @author:chenssy 101 | * @date : 2016年4月30日 下午9:10:12 102 | */ 103 | @SuppressWarnings("resource") 104 | public static long getFileSize(File file) throws Exception { 105 | long size = 0; 106 | if (file.exists()) { 107 | FileInputStream fis = null; 108 | fis = new FileInputStream(file); 109 | size = fis.available(); 110 | } else { 111 | file.createNewFile(); 112 | } 113 | return size; 114 | } 115 | 116 | /** 117 | * 删除所有文件,包括文件夹 118 | * 119 | * @author : chenssy 120 | * @date : 2016年5月23日 下午12:41:08 121 | * 122 | * @param dirpath 123 | */ 124 | public void deleteAll(String dirpath) { 125 | File path = new File(dirpath); 126 | try { 127 | if (!path.exists()) 128 | return;// 目录不存在退出 129 | if (path.isFile()) // 如果是文件删除 130 | { 131 | path.delete(); 132 | return; 133 | } 134 | File[] files = path.listFiles();// 如果目录中有文件递归删除文件 135 | for (int i = 0; i < files.length; i++) { 136 | deleteAll(files[i].getAbsolutePath()); 137 | } 138 | path.delete(); 139 | 140 | } catch (Exception e) { 141 | e.printStackTrace(); 142 | } 143 | } 144 | 145 | /** 146 | * 复制文件或者文件夹 147 | * 148 | * @author : chenssy 149 | * @date : 2016年5月23日 下午12:41:59 150 | * 151 | * @param inputFile 152 | * 源文件 153 | * @param outputFile 154 | * 目的文件 155 | * @param isOverWrite 156 | * 是否覆盖文件 157 | * @throws java.io.IOException 158 | */ 159 | public static void copy(File inputFile, File outputFile, boolean isOverWrite) 160 | throws IOException { 161 | if (!inputFile.exists()) { 162 | throw new RuntimeException(inputFile.getPath() + "源目录不存在!"); 163 | } 164 | copyPri(inputFile, outputFile, isOverWrite); 165 | } 166 | 167 | /** 168 | * 复制文件或者文件夹 169 | * 170 | * @author : chenssy 171 | * @date : 2016年5月23日 下午12:43:24 172 | * 173 | * @param inputFile 174 | * 源文件 175 | * @param outputFile 176 | * 目的文件 177 | * @param isOverWrite 178 | * 是否覆盖文件 179 | * @throws java.io.IOException 180 | */ 181 | private static void copyPri(File inputFile, File outputFile, boolean isOverWrite) throws IOException { 182 | if (inputFile.isFile()) { //文件 183 | copySimpleFile(inputFile, outputFile, isOverWrite); 184 | } else { 185 | if (!outputFile.exists()) { //文件夹 186 | outputFile.mkdirs(); 187 | } 188 | // 循环子文件夹 189 | for (File child : inputFile.listFiles()) { 190 | copy(child, new File(outputFile.getPath() + "/" + child.getName()), isOverWrite); 191 | } 192 | } 193 | } 194 | 195 | /** 196 | * 复制单个文件 197 | * 198 | * @author : chenssy 199 | * @date : 2016年5月23日 下午12:44:07 200 | * 201 | * @param inputFile 202 | * 源文件 203 | * @param outputFile 204 | * 目的文件 205 | * @param isOverWrite 206 | * 是否覆盖 207 | * @throws java.io.IOException 208 | */ 209 | private static void copySimpleFile(File inputFile, File outputFile, 210 | boolean isOverWrite) throws IOException { 211 | if (outputFile.exists()) { 212 | if (isOverWrite) { //可以覆盖 213 | if (!outputFile.delete()) { 214 | throw new RuntimeException(outputFile.getPath() + "无法覆盖!"); 215 | } 216 | } else { 217 | // 不允许覆盖 218 | return; 219 | } 220 | } 221 | InputStream in = new FileInputStream(inputFile); 222 | OutputStream out = new FileOutputStream(outputFile); 223 | byte[] buffer = new byte[1024]; 224 | int read = 0; 225 | while ((read = in.read(buffer)) != -1) { 226 | out.write(buffer, 0, read); 227 | } 228 | in.close(); 229 | out.close(); 230 | } 231 | 232 | /** 233 | * 获取文件的MD5 234 | * 235 | * @author : chenssy 236 | * @date : 2016年5月23日 下午12:50:38 237 | * 238 | * @param file 239 | * 文件 240 | * @return 241 | */ 242 | public static String getFileMD5(File file){ 243 | if (!file.exists() || !file.isFile()) { 244 | return null; 245 | } 246 | MessageDigest digest = null; 247 | FileInputStream in = null; 248 | byte buffer[] = new byte[1024]; 249 | int len; 250 | try { 251 | digest = MessageDigest.getInstance("MD5"); 252 | in = new FileInputStream(file); 253 | while ((len = in.read(buffer, 0, 1024)) != -1) { 254 | digest.update(buffer, 0, len); 255 | } 256 | in.close(); 257 | } catch (Exception e) { 258 | e.printStackTrace(); 259 | return null; 260 | } 261 | BigInteger bigInt = new BigInteger(1, digest.digest()); 262 | return bigInt.toString(16); 263 | } 264 | 265 | /** 266 | * 获取文件的后缀 267 | * 268 | * @author : chenssy 269 | * @date : 2016年5月23日 下午12:51:59 270 | * 271 | * @param file 272 | * 文件 273 | * @return 274 | */ 275 | public static String getFileSuffix(String file) { 276 | if (file == null) { 277 | return null; 278 | } 279 | int extIndex = file.lastIndexOf(EXTENSION_SEPARATOR); 280 | if (extIndex == -1) { 281 | return null; 282 | } 283 | int folderIndex = file.lastIndexOf(FOLDER_SEPARATOR); 284 | if (folderIndex > extIndex) { 285 | return null; 286 | } 287 | return file.substring(extIndex + 1); 288 | } 289 | 290 | /** 291 | * 文件重命名 292 | * 293 | * @author : chenssy 294 | * @date : 2016年5月23日 下午12:56:05 295 | * 296 | * @param oldPath 297 | * 老文件 298 | * @param newPath 299 | * 新文件 300 | */ 301 | public boolean renameDir(String oldPath, String newPath) { 302 | File oldFile = new File(oldPath);// 文件或目录 303 | File newFile = new File(newPath);// 文件或目录 304 | 305 | return oldFile.renameTo(newFile);// 重命名 306 | } 307 | } 308 | -------------------------------------------------------------------------------- /src/main/java/com/JUtils/file/ZipUitls.java: -------------------------------------------------------------------------------- 1 | package com.JUtils.file; 2 | 3 | import java.io.BufferedOutputStream; 4 | import java.io.File; 5 | import java.io.FileInputStream; 6 | import java.io.FileNotFoundException; 7 | import java.io.FileOutputStream; 8 | import java.io.IOException; 9 | import java.util.zip.ZipEntry; 10 | import java.util.zip.ZipOutputStream; 11 | 12 | /** 13 | * 文件压缩、解压工具类。文件压缩格式为zip 14 | * 15 | * @Author:chenssy 16 | * @date:2016年5月24日 下午9:16:01 17 | */ 18 | public class ZipUitls { 19 | /** 文件后缀名 */ 20 | private static final String ZIP_FILE_SUFFIX = ".zip"; 21 | 22 | /** 23 | * 压缩文件 24 | * 25 | * @author:chenssy 26 | * @date : 2016年5月24日 下午9:56:36 27 | * 28 | * @param resourcePath 29 | * 源文件 30 | * @param targetPath 31 | * 目的文件,保存文件路径 32 | */ 33 | public static void zipFile(String resourcePath,String targetPath){ 34 | File resourcesFile = new File(resourcePath); 35 | File targetFile = new File(targetPath); 36 | 37 | //目的文件不存在,则新建 38 | if(!targetFile.exists()){ 39 | targetFile.mkdirs(); 40 | } 41 | //文件名 42 | String targetName = resourcesFile.getName() + ZIP_FILE_SUFFIX; 43 | 44 | ZipOutputStream out = null; 45 | try { 46 | FileOutputStream outputStream = new FileOutputStream(targetPath+"//"+targetName); 47 | out = new ZipOutputStream(new BufferedOutputStream(outputStream)); 48 | 49 | compressedFile(out, resourcesFile, ""); 50 | } catch (FileNotFoundException e) { 51 | e.printStackTrace(); 52 | }finally{ 53 | if (out != null) { 54 | try { 55 | out.close(); 56 | } catch (IOException e) { 57 | e.printStackTrace(); 58 | } 59 | } 60 | } 61 | } 62 | 63 | /** 64 | * 65 | * @author:chenssy 66 | * @date : 2016年5月24日 下午10:00:22 67 | * 68 | * @param out 69 | * @param resourcesFile 70 | * @param dir 71 | */ 72 | private static void compressedFile(ZipOutputStream out, File file, String dir) { 73 | FileInputStream fis = null; 74 | try { 75 | if (file.isDirectory()) { //文件夹 76 | // 得到文件列表信息 77 | File[] files = file.listFiles(); 78 | // 将文件夹添加到下一级打包目录 79 | out.putNextEntry(new ZipEntry(dir + "/")); 80 | 81 | dir = dir.length() == 0 ? "" : dir + "/"; 82 | 83 | // 循环将文件夹中的文件打包 84 | for (int i = 0; i < files.length; i++) { 85 | compressedFile(out, files[i], dir + files[i].getName()); // 递归处理 86 | } 87 | } else { //如果是文件则打包处理 88 | fis = new FileInputStream(file); 89 | 90 | out.putNextEntry(new ZipEntry(dir)); 91 | // 进行写操作 92 | int j = 0; 93 | byte[] buffer = new byte[1024]; 94 | while ((j = fis.read(buffer)) > 0) { 95 | out.write(buffer, 0, j); 96 | } 97 | // 关闭输入流 98 | } 99 | } catch (FileNotFoundException e) { 100 | e.printStackTrace(); 101 | } catch (IOException e) { 102 | e.printStackTrace(); 103 | } finally{ 104 | if(fis != null){ 105 | try { 106 | fis.close(); 107 | } catch (IOException e) { 108 | e.printStackTrace(); 109 | } 110 | } 111 | } 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /src/main/java/com/JUtils/image/ImageUtil.java: -------------------------------------------------------------------------------- 1 | package com.JUtils.image; 2 | 3 | import java.awt.AlphaComposite; 4 | import java.awt.Color; 5 | import java.awt.Font; 6 | import java.awt.Graphics2D; 7 | import java.awt.Image; 8 | import java.awt.color.ColorSpace; 9 | import java.awt.image.BufferedImage; 10 | import java.awt.image.ColorConvertOp; 11 | import java.io.File; 12 | import java.io.FileInputStream; 13 | import java.io.IOException; 14 | 15 | import javax.imageio.ImageIO; 16 | 17 | /** 18 | * 图像处理
19 | * 对图片进行压缩、水印、伸缩变换、透明处理、格式转换操作 20 | * 21 | * @Author:chenssy 22 | * @date:2015年3月19日 23 | */ 24 | public class ImageUtil { 25 | 26 | public static final float DEFAULT_QUALITY = 0.2125f ; 27 | 28 | 29 | /** 30 | * 31 | * 添加图片水印操作(物理存盘,使用默认格式) 32 | * 33 | * @param imgPath 34 | * 待处理图片 35 | * @param markPath 36 | * 水印图片 37 | * @param x 38 | * 水印位于图片左上角的 x 坐标值 39 | * @param y 40 | * 水印位于图片左上角的 y 坐标值 41 | * @param alpha 42 | * 水印透明度 0.1f ~ 1.0f 43 | * @param destPath 44 | * 文件存放路径 45 | * @throws Exception 46 | * 47 | */ 48 | public static void addWaterMark(String imgPath, String markPath, int x, int y, float alpha,String destPath) throws Exception{ 49 | try { 50 | BufferedImage bufferedImage = addWaterMark(imgPath, markPath, x, y, alpha); 51 | ImageIO.write(bufferedImage, imageFormat(imgPath), new File(destPath)); 52 | } catch (Exception e) { 53 | throw new RuntimeException("添加图片水印异常"); 54 | } 55 | } 56 | 57 | 58 | /** 59 | * 60 | * 添加图片水印操作(物理存盘,自定义格式) 61 | * 62 | * @param imgPath 63 | * 待处理图片 64 | * @param markPath 65 | * 水印图片 66 | * @param x 67 | * 水印位于图片左上角的 x 坐标值 68 | * @param y 69 | * 水印位于图片左上角的 y 坐标值 70 | * @param alpha 71 | * 水印透明度 0.1f ~ 1.0f 72 | * @param format 73 | * 添加水印后存储的格式 74 | * @param destPath 75 | * 文件存放路径 76 | * @throws Exception 77 | * 78 | */ 79 | public static void addWaterMark(String imgPath, String markPath, int x, int y, float alpha,String format,String destPath) throws Exception{ 80 | try { 81 | BufferedImage bufferedImage = addWaterMark(imgPath, markPath, x, y, alpha); 82 | ImageIO.write(bufferedImage,format , new File(destPath)); 83 | } catch (Exception e) { 84 | throw new RuntimeException("添加图片水印异常"); 85 | } 86 | } 87 | 88 | 89 | /** 90 | * 91 | * 添加图片水印操作,返回BufferedImage对象 92 | * 93 | * @param imgPath 94 | * 待处理图片 95 | * @param markPath 96 | * 水印图片 97 | * @param x 98 | * 水印位于图片左上角的 x 坐标值 99 | * @param y 100 | * 水印位于图片左上角的 y 坐标值 101 | * @param alpha 102 | * 水印透明度 0.1f ~ 1.0f 103 | * @return 104 | * 处理后的图片对象 105 | * @throws Exception 106 | * 107 | */ 108 | public static BufferedImage addWaterMark(String imgPath, String markPath, int x, int y, float alpha) throws Exception{ 109 | BufferedImage targetImage = null; 110 | try { 111 | // 加载待处理图片文件 112 | Image img = ImageIO.read(new File(imgPath)); 113 | 114 | //创建目标图象文件 115 | targetImage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB); 116 | Graphics2D g = targetImage.createGraphics(); 117 | g.drawImage(img, 0, 0, null); 118 | 119 | // 加载水印图片文件 120 | Image markImg = ImageIO.read(new File(markPath)); 121 | g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha)); 122 | g.drawImage(markImg, x, y, null); 123 | g.dispose(); 124 | } catch (Exception e) { 125 | throw new RuntimeException("添加图片水印操作异常"); 126 | } 127 | return targetImage; 128 | 129 | } 130 | 131 | /** 132 | * 133 | * 添加文字水印操作(物理存盘,使用默认格式) 134 | * 135 | * @param imgPath 136 | * 待处理图片 137 | * @param text 138 | * 水印文字 139 | * @param font 140 | * 水印字体信息 不写默认值为宋体 141 | * @param color 142 | * 水印字体颜色 143 | * @param x 144 | * 水印位于图片左上角的 x 坐标值 145 | * @param y 146 | * 水印位于图片左上角的 y 坐标值 147 | * @param alpha 148 | * 水印透明度 0.1f ~ 1.0f 149 | * @param format 150 | * 添加水印后存储的格式 151 | * @param destPath 152 | * 文件存放路径 153 | * @throws Exception 154 | */ 155 | public static void addTextMark(String imgPath, String text, Font font, Color color, float x, float y, float alpha,String destPath) throws Exception{ 156 | try { 157 | BufferedImage bufferedImage = addTextMark(imgPath, text, font, color, x, y, alpha); 158 | ImageIO.write(bufferedImage, imageFormat(imgPath), new File(destPath)); 159 | } catch (Exception e) { 160 | throw new RuntimeException("图片添加文字水印异常"); 161 | } 162 | } 163 | 164 | /** 165 | * 166 | * 添加文字水印操作(物理存盘,自定义格式) 167 | * 168 | * @param imgPath 169 | * 待处理图片 170 | * @param text 171 | * 水印文字 172 | * @param font 173 | * 水印字体信息 不写默认值为宋体 174 | * @param color 175 | * 水印字体颜色 176 | * @param x 177 | * 水印位于图片左上角的 x 坐标值 178 | * @param y 179 | * 水印位于图片左上角的 y 坐标值 180 | * @param alpha 181 | * 水印透明度 0.1f ~ 1.0f 182 | * @param format 183 | * 添加水印后存储的格式 184 | * @param destPath 185 | * 文件存放路径 186 | * @throws Exception 187 | */ 188 | public static void addTextMark(String imgPath, String text, Font font, Color color, float x, float y, float alpha,String format,String destPath) throws Exception{ 189 | try { 190 | BufferedImage bufferedImage = addTextMark(imgPath, text, font, color, x, y, alpha); 191 | ImageIO.write(bufferedImage, format, new File(destPath)); 192 | } catch (Exception e) { 193 | throw new RuntimeException("图片添加文字水印异常"); 194 | } 195 | } 196 | 197 | /** 198 | * 199 | * 添加文字水印操作,返回BufferedImage对象 200 | * 201 | * @param imgPath 202 | * 待处理图片 203 | * @param text 204 | * 水印文字 205 | * @param font 206 | * 水印字体信息 不写默认值为宋体 207 | * @param color 208 | * 水印字体颜色 209 | * @param x 210 | * 水印位于图片左上角的 x 坐标值 211 | * @param y 212 | * 水印位于图片左上角的 y 坐标值 213 | * @param alpha 214 | * 水印透明度 0.1f ~ 1.0f 215 | * @return 216 | * 处理后的图片对象 217 | * @throws Exception 218 | */ 219 | 220 | public static BufferedImage addTextMark(String imgPath, String text, Font font, Color color, float x, float y, float alpha) throws Exception{ 221 | BufferedImage targetImage = null; 222 | try { 223 | Font Dfont = (font == null) ? new Font("宋体", 20, 13) : font; 224 | Image img = ImageIO.read(new File(imgPath)); 225 | //创建目标图像文件 226 | targetImage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB); 227 | Graphics2D g = targetImage.createGraphics(); 228 | g.drawImage(img, 0, 0, null); 229 | g.setColor(color); 230 | g.setFont(Dfont); 231 | g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha)); 232 | g.drawString(text, x, y); 233 | g.dispose(); 234 | } catch (Exception e) { 235 | throw new RuntimeException("添加文字水印操作异常"); 236 | } 237 | return targetImage; 238 | } 239 | 240 | 241 | 242 | /** 243 | * 244 | * 245 | * 246 | * 压缩图片操作(文件物理存盘,使用默认格式) 247 | * 248 | * @param imgPath 249 | * 待处理图片 250 | * @param quality 251 | * 图片质量(0-1之間的float值) 252 | * @param width 253 | * 输出图片的宽度 输入负数参数表示用原来图片宽 254 | * @param height 255 | * 输出图片的高度 输入负数参数表示用原来图片高 256 | * @param autoSize 257 | * 是否等比缩放 true表示进行等比缩放 false表示不进行等比缩放 258 | * @param format 259 | * 压缩后存储的格式 260 | * @param destPath 261 | * 文件存放路径 262 | * 263 | * @throws Exception 264 | */ 265 | public static void compressImage(String imgPath,float quality,int width, int height, boolean autoSize,String destPath)throws Exception{ 266 | try { 267 | BufferedImage bufferedImage = compressImage(imgPath, quality, width, height, autoSize); 268 | ImageIO.write(bufferedImage, imageFormat(imgPath), new File(destPath)); 269 | } catch (Exception e) { 270 | throw new RuntimeException("图片压缩异常"); 271 | } 272 | 273 | } 274 | 275 | 276 | /** 277 | * 278 | * 压缩图片操作(文件物理存盘,可自定义格式) 279 | * 280 | * @param imgPath 281 | * 待处理图片 282 | * @param quality 283 | * 图片质量(0-1之間的float值) 284 | * @param width 285 | * 输出图片的宽度 输入负数参数表示用原来图片宽 286 | * @param height 287 | * 输出图片的高度 输入负数参数表示用原来图片高 288 | * @param autoSize 289 | * 是否等比缩放 true表示进行等比缩放 false表示不进行等比缩放 290 | * @param format 291 | * 压缩后存储的格式 292 | * @param destPath 293 | * 文件存放路径 294 | * 295 | * @throws Exception 296 | */ 297 | public static void compressImage(String imgPath,float quality,int width, int height, boolean autoSize,String format,String destPath)throws Exception{ 298 | try { 299 | BufferedImage bufferedImage = compressImage(imgPath, quality, width, height, autoSize); 300 | ImageIO.write(bufferedImage, format, new File(destPath)); 301 | } catch (Exception e) { 302 | throw new RuntimeException("图片压缩异常"); 303 | } 304 | } 305 | 306 | 307 | /** 308 | * 309 | * 压缩图片操作,返回BufferedImage对象 310 | * 311 | * @param imgPath 312 | * 待处理图片 313 | * @param quality 314 | * 图片质量(0-1之間的float值) 315 | * @param width 316 | * 输出图片的宽度 输入负数参数表示用原来图片宽 317 | * @param height 318 | * 输出图片的高度 输入负数参数表示用原来图片高 319 | * @param autoSize 320 | * 是否等比缩放 true表示进行等比缩放 false表示不进行等比缩放 321 | * @return 322 | * 处理后的图片对象 323 | * @throws Exception 324 | */ 325 | public static BufferedImage compressImage(String imgPath,float quality,int width, int height, boolean autoSize)throws Exception{ 326 | BufferedImage targetImage = null; 327 | if(quality<0F||quality>1F){ 328 | quality = DEFAULT_QUALITY; 329 | } 330 | try { 331 | Image img = ImageIO.read(new File(imgPath)); 332 | //如果用户输入的图片参数合法则按用户定义的复制,负值参数表示执行默认值 333 | int newwidth =( width > 0 ) ? width : img.getWidth(null); 334 | //如果用户输入的图片参数合法则按用户定义的复制,负值参数表示执行默认值 335 | int newheight = ( height > 0 )? height: img.getHeight(null); 336 | //如果是自适应大小则进行比例缩放 337 | if(autoSize){ 338 | // 为等比缩放计算输出的图片宽度及高度 339 | double Widthrate = ((double) img.getWidth(null)) / (double) width + 0.1; 340 | double heightrate = ((double) img.getHeight(null))/ (double) height + 0.1; 341 | double rate = Widthrate > heightrate ? Widthrate : heightrate; 342 | newwidth = (int) (((double) img.getWidth(null)) / rate); 343 | newheight = (int) (((double) img.getHeight(null)) / rate); 344 | } 345 | //创建目标图像文件 346 | targetImage = new BufferedImage(newwidth,newheight,BufferedImage.TYPE_INT_RGB); 347 | Graphics2D g = targetImage.createGraphics(); 348 | g.drawImage(img, 0, 0, newwidth, newheight, null); 349 | //如果添加水印或者文字则继续下面操作,不添加的话直接返回目标文件---------------------- 350 | g.dispose(); 351 | 352 | } catch (Exception e) { 353 | throw new RuntimeException("图片压缩操作异常"); 354 | } 355 | return targetImage; 356 | } 357 | 358 | 359 | 360 | /** 361 | * 图片黑白化操作(文件物理存盘,使用默认格式) 362 | * 363 | * @param bufferedImage 364 | * 处理的图片对象 365 | * @param destPath 366 | * 目标文件地址 367 | * @throws Exception 368 | * 369 | */ 370 | public static void imageGray(String imgPath, String destPath)throws Exception{ 371 | imageGray(imgPath, imageFormat(imgPath), destPath); 372 | } 373 | 374 | 375 | /** 376 | * 图片黑白化操作(文件物理存盘,可自定义格式) 377 | * 378 | * @param bufferedImage 379 | * 处理的图片对象 380 | * @param format 381 | * 图片格式 382 | * @param destPath 383 | * 目标文件地址 384 | * @throws Exception 385 | * 386 | */ 387 | public static void imageGray(String imgPath,String format, String destPath)throws Exception{ 388 | try { 389 | BufferedImage bufferedImage = ImageIO.read(new File(imgPath)); 390 | ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY); 391 | ColorConvertOp op = new ColorConvertOp(cs, null); 392 | bufferedImage = op.filter(bufferedImage, null); 393 | ImageIO.write(bufferedImage, format , new File(destPath)); 394 | } catch (Exception e) { 395 | throw new RuntimeException("图片灰白化异常"); 396 | } 397 | } 398 | 399 | 400 | 401 | /** 402 | * 图片透明化操作(文件物理存盘,使用默认格式) 403 | * 404 | * @param imgPath 405 | * 图片路径 406 | * @param destPath 407 | * 图片存放路径 408 | * @throws Exception 409 | */ 410 | public static void imageLucency(String imgPath,String destPath)throws Exception{ 411 | try { 412 | BufferedImage bufferedImage = imageLucency(imgPath); 413 | ImageIO.write(bufferedImage, imageFormat(imgPath), new File(destPath)); 414 | } catch (Exception e) { 415 | throw new RuntimeException("图片透明化异常"); 416 | } 417 | } 418 | 419 | 420 | /** 421 | * 图片透明化操作(文件物理存盘,可自定义格式) 422 | * 423 | * @param imgPath 424 | * 图片路径 425 | * @param format 426 | * 图片格式 427 | * @param destPath 428 | * 图片存放路径 429 | * @throws Exception 430 | */ 431 | public static void imageLucency(String imgPath,String format,String destPath)throws Exception{ 432 | try { 433 | BufferedImage bufferedImage = imageLucency(imgPath); 434 | ImageIO.write(bufferedImage, format, new File(destPath)); 435 | } catch (Exception e) { 436 | throw new RuntimeException("图片透明化异常"); 437 | } 438 | } 439 | 440 | /** 441 | * 图片透明化操作返回BufferedImage对象 442 | * 443 | * @param imgPath 444 | * 图片路径 445 | * @return 446 | * 透明化后的图片对象 447 | * @throws Exception 448 | */ 449 | public static BufferedImage imageLucency(String imgPath)throws Exception{ 450 | BufferedImage targetImage = null; 451 | try { 452 | //读取图片 453 | BufferedImage img = ImageIO.read(new FileInputStream(imgPath)); 454 | //透明度 455 | int alpha = 0; 456 | //执行透明化 457 | executeRGB(img, alpha); 458 | targetImage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB); 459 | Graphics2D g = targetImage.createGraphics(); 460 | g.drawImage(img, 0, 0, null); 461 | g.dispose(); 462 | } catch (Exception e) { 463 | throw new RuntimeException("图片透明化执行异常"); 464 | } 465 | return targetImage; 466 | } 467 | 468 | /** 469 | * 执行透明化的核心算法 470 | * 471 | * @param img 472 | * 图片对象 473 | * @param alpha 474 | * 透明度 475 | * @throws Exception 476 | */ 477 | public static void executeRGB(BufferedImage img, int alpha) throws Exception{ 478 | int rgb = 0;//RGB值 479 | //x表示BufferedImage的x坐标,y表示BufferedImage的y坐标 480 | for(int x=img.getMinX();x> 16 ; 485 | int G= (rgb & 0xff00 ) >> 8 ; 486 | int B= (rgb & 0xff ); 487 | if(((255-R)<30) && ((255-G)<30) && ((255-B)<30)){ 488 | rgb = ((alpha + 1) << 24) | (rgb & 0x00ffffff); 489 | img.setRGB(x, y, rgb); 490 | } 491 | } 492 | } 493 | } 494 | 495 | 496 | /** 497 | * 图片格式转化操作(文件物理存盘) 498 | * 499 | * @param imgPath 500 | * 原始图片存放地址 501 | * @param format 502 | * 待转换的格式 jpeg,gif,png,bmp等 503 | * @param destPath 504 | * 目标文件地址 505 | * @throws Exception 506 | */ 507 | public static void formatConvert(String imgPath, String format, String destPath)throws Exception{ 508 | try { 509 | BufferedImage bufferedImage = ImageIO.read(new File(imgPath)); 510 | ImageIO.write(bufferedImage, format, new File(destPath)); 511 | } catch (IOException e) { 512 | throw new RuntimeException("文件格式转换出错"); 513 | } 514 | } 515 | 516 | 517 | 518 | /** 519 | * 图片格式转化操作返回BufferedImage对象 520 | * 521 | * @param bufferedImage 522 | * BufferedImage图片转换对象 523 | * @param format 524 | * 待转换的格式 jpeg,gif,png,bmp等 525 | * @param destPath 526 | * 目标文件地址 527 | * @throws Exception 528 | */ 529 | public static void formatConvert(BufferedImage bufferedImag, String format, String destPath)throws Exception{ 530 | try { 531 | ImageIO.write(bufferedImag, format, new File(destPath)); 532 | } catch (IOException e) { 533 | throw new RuntimeException("文件格式转换出错"); 534 | } 535 | } 536 | 537 | 538 | /** 539 | * 获取图片文件的真实格式信息 540 | * 541 | * @param imgPath 542 | * 图片原文件存放地址 543 | * @return 544 | * 图片格式 545 | * @throws Exception 546 | */ 547 | public static String imageFormat(String imgPath)throws Exception{ 548 | String[] filess = imgPath.split("\\\\"); 549 | String[] formats = filess[filess.length - 1].split("\\."); 550 | return formats[formats.length - 1]; 551 | } 552 | 553 | } -------------------------------------------------------------------------------- /src/main/java/com/JUtils/math/BigDecimalUtils.java: -------------------------------------------------------------------------------- 1 | package com.JUtils.math; 2 | 3 | import java.math.BigDecimal; 4 | 5 | import com.JUtils.base.ValidateHelper; 6 | 7 | /** 8 | * 提供精确的加减乘除运算 9 | * 10 | * @Author:chenssy 11 | * @date:2014年9月15日 12 | */ 13 | public class BigDecimalUtils { 14 | 15 | /** 16 | * 默认保留位:2 17 | */ 18 | private static int DEFAULT_SCALE = 2; 19 | 20 | /** 21 | * 默认四舍五入规则为:向上舍入 22 | */ 23 | private static int DEFAULT_ROUND = BigDecimal.ROUND_HALF_UP; 24 | 25 | /** 26 | * 27 | * 加法运算 28 | * @autor:chenssy 29 | * @date:2014年9月15日 30 | * 31 | * @param v1 加数 32 | * @param v2 被加数 33 | * @return 34 | */ 35 | public static String add(String v1,String v2){ 36 | BigDecimal b1 = new BigDecimal(v1); 37 | BigDecimal b2 = new BigDecimal(v2); 38 | return b1.add(b2).toString(); 39 | } 40 | 41 | /** 42 | * 除法运算
43 | * 当发生除不尽的情况时,由scale参数指定精度,以后的数字四舍五入。 44 | * @autor:chenssy 45 | * @date:2014年9月15日 46 | * 47 | * @param v1 48 | * 除数 49 | * @param v2 50 | * 被除数 51 | * @param scale 52 | * 精确精度 53 | * @return 54 | */ 55 | public static String div(String v1, String v2, int scale, int round) { 56 | if (scale < 0) { 57 | throw new IllegalArgumentException( 58 | "The scale must be a positive integer or zero"); 59 | } 60 | 61 | if (ValidateHelper.isEmpty(scale)) { 62 | scale = DEFAULT_SCALE; 63 | } 64 | 65 | if (ValidateHelper.isEmpty(round)) { 66 | round = DEFAULT_ROUND; 67 | } 68 | 69 | BigDecimal b1 = new BigDecimal(v1); 70 | BigDecimal b2 = new BigDecimal(v2); 71 | return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).toString(); 72 | } 73 | 74 | /** 75 | * 比较两个数
76 | * v1 > v2 return 1
77 | * v1 = v2 return 0
78 | * v1 < v2 return -1 79 | * @autor:chenssy 80 | * @date:2014年9月15日 81 | * 82 | * @param v1 83 | * 比较数 84 | * @param v2 85 | * 被比较数 86 | * @return 87 | */ 88 | public static int compareTo(String v1,String v2){ 89 | BigDecimal b1 = new BigDecimal(v1); 90 | BigDecimal b2 = new BigDecimal(v2); 91 | return b1.compareTo(b2); 92 | } 93 | 94 | /** 95 | * 返回较小数 96 | * @autor:chenssy 97 | * @date:2014年9月15日 98 | * 99 | * @param v1 100 | * @param v2 101 | * @return 102 | */ 103 | public static String returnMin(String v1,String v2){ 104 | BigDecimal b1 = new BigDecimal(v1); 105 | BigDecimal b2 = new BigDecimal(v2); 106 | return b1.min(b2).toString(); 107 | } 108 | 109 | /** 110 | * 返回较大数 111 | * @autor:chenssy 112 | * @date:2014年9月15日 113 | * 114 | * @param v1 115 | * @param v2 116 | * @return 117 | */ 118 | public static String returnMax(String v1,String v2){ 119 | BigDecimal b1 = new BigDecimal(v1); 120 | BigDecimal b2 = new BigDecimal(v2); 121 | return b1.max(b2).toString(); 122 | } 123 | 124 | /** 125 | * 处理BigDecimal数据,保留scale位小数 126 | * @author:chenssy 127 | * @date:2014年10月21日 128 | * 129 | * @param value 130 | * @param scale 131 | * @return 132 | */ 133 | public static BigDecimal getValue(BigDecimal value,int scale){ 134 | if(!ValidateHelper.isEmpty(value)){ 135 | return value.setScale(scale, BigDecimal.ROUND_HALF_UP); 136 | } 137 | return value; 138 | } 139 | 140 | /** 141 | * 将object转换为Bigdecimal 142 | * 143 | * @author:chenssy 144 | * @date:2014年10月17日 145 | * 146 | * @param value 147 | * 待转换的数值 148 | * @return 149 | */ 150 | public static BigDecimal getBigDecimal(Object value){ 151 | BigDecimal resultValue = new BigDecimal(0); 152 | if(value instanceof String){ 153 | resultValue = new BigDecimal((String)value); 154 | } 155 | else if(value instanceof Integer){ 156 | resultValue = new BigDecimal((Integer)value); 157 | } 158 | else if(value instanceof Long){ 159 | resultValue = new BigDecimal((Long)value); 160 | } 161 | else if(value instanceof Double){ 162 | resultValue = new BigDecimal((Double)value); 163 | } 164 | else{ 165 | resultValue = (BigDecimal) value; 166 | } 167 | 168 | return resultValue; 169 | } 170 | 171 | 172 | /** 173 | * 将object转换为Bigdecimal,若object为空,则返回resultValue 174 | * 175 | * @autor:chenssy 176 | * @date:2014年9月20日 177 | * 178 | * @param value 179 | * @return 180 | */ 181 | public static BigDecimal getBigDecimal(Object value,BigDecimal resultValue){ 182 | if(ValidateHelper.isEmpty(value)){ 183 | return resultValue; 184 | } 185 | 186 | resultValue = getBigDecimal(resultValue); 187 | 188 | return resultValue; 189 | } 190 | 191 | /** 192 | * 将BigDecimal 转换成Long 193 | * @autor:chenssy 194 | * @date:2014年9月20日 195 | * 196 | * @param value 197 | * @return 198 | */ 199 | public static Long bigDecimalToLong(BigDecimal value){ 200 | if(value != null){ 201 | return new Long(value.longValue()); 202 | } 203 | return null; 204 | } 205 | 206 | /** 207 | * 将BigDecimal 转换成integer 208 | * @autor:huangc 209 | * @date:2014年9月20日 210 | * 211 | * @param value 212 | * @return 213 | */ 214 | public static Integer bigDecimalToInteger(BigDecimal value){ 215 | if(value != null){ 216 | return new Integer(value.intValue()); 217 | } 218 | return null; 219 | } 220 | } 221 | -------------------------------------------------------------------------------- /src/main/java/com/JUtils/math/RandomUtils.java: -------------------------------------------------------------------------------- 1 | package com.JUtils.math; 2 | 3 | import java.util.Random; 4 | 5 | /** 6 | * 随机数工具类 7 | * 8 | * @Author:chenssy 9 | * @date:2014年8月11日 10 | */ 11 | public class RandomUtils { 12 | private static final String ALL_CHAR = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; 13 | private static final String LETTER_CHAR = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; 14 | private static final String NUMBER_CHAR = "0123456789"; 15 | 16 | /** 17 | * 获取定长的随机数,包含大小写、数字 18 | * @autor:chenssy 19 | * @date:2014年8月11日 20 | * 21 | * @param length 22 | * 随机数长度 23 | * @return 24 | */ 25 | public static String generateString(int length) { 26 | StringBuffer sb = new StringBuffer(); 27 | Random random = new Random(); 28 | for (int i = 0; i < length; i++) { 29 | sb.append(ALL_CHAR.charAt(random.nextInt(ALL_CHAR.length()))); 30 | } 31 | return sb.toString(); 32 | } 33 | 34 | /** 35 | * 获取定长的随机数,包含大小写字母 36 | * @autor:chenssy 37 | * @date:2014年8月11日 38 | * 39 | * @param length 40 | * 随机数长度 41 | * @return 42 | */ 43 | public static String generateMixString(int length) { 44 | StringBuffer sb = new StringBuffer(); 45 | Random random = new Random(); 46 | for (int i = 0; i < length; i++) { 47 | sb.append(LETTER_CHAR.charAt(random.nextInt(LETTER_CHAR.length()))); 48 | } 49 | return sb.toString(); 50 | } 51 | 52 | /** 53 | * 获取定长的随机数,只包含小写字母 54 | * @autor:chenssy 55 | * @date:2014年8月11日 56 | * 57 | * @param length 58 | * 随机数长度 59 | * @return 60 | */ 61 | public static String generateLowerString(int length) { 62 | return generateMixString(length).toLowerCase(); 63 | } 64 | 65 | /** 66 | * 获取定长的随机数,只包含大写字母 67 | * @autor:chenssy 68 | * @date:2014年8月11日 69 | * 70 | * @param length 71 | * 随机数长度 72 | * @return 73 | */ 74 | public static String generateUpperString(int length) { 75 | return generateMixString(length).toUpperCase(); 76 | } 77 | 78 | /** 79 | * 获取定长的随机数,只包含数字 80 | * @autor:chenssy 81 | * @date:2014年8月11日 82 | * 83 | * @param length 84 | * 随机数长度 85 | * @return 86 | */ 87 | public static String generateNumberString(int length){ 88 | StringBuffer sb = new StringBuffer(); 89 | Random random = new Random(); 90 | for (int i = 0; i < length; i++) { 91 | sb.append(NUMBER_CHAR.charAt(random.nextInt(NUMBER_CHAR.length()))); 92 | } 93 | return sb.toString(); 94 | } 95 | 96 | } 97 | -------------------------------------------------------------------------------- /src/main/java/com/JUtils/sensitiveword/SensitiveWordInit.java: -------------------------------------------------------------------------------- 1 | package com.JUtils.sensitiveword; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.File; 5 | import java.io.FileInputStream; 6 | import java.io.InputStreamReader; 7 | import java.util.HashMap; 8 | import java.util.HashSet; 9 | import java.util.Iterator; 10 | import java.util.Map; 11 | import java.util.Set; 12 | 13 | /** 14 | * 初始化敏感词库,将敏感词加入到HashMap中,构建DFA算法模型 15 | * 16 | * @Author : chenssy 17 | * @Date : 2014年4月20日 下午2:27:06 18 | */ 19 | public class SensitiveWordInit { 20 | private String ENCODING = "GBK"; //字符编码 21 | @SuppressWarnings("rawtypes") 22 | public HashMap sensitiveWordMap; 23 | 24 | SensitiveWordInit(){ 25 | super(); 26 | } 27 | 28 | /** 29 | * @author chenssy 30 | * @date 2014年4月20日 下午2:28:32 31 | * @version 1.0 32 | */ 33 | @SuppressWarnings("rawtypes") 34 | Map initKeyWord(){ 35 | try { 36 | //读取敏感词库 37 | Set keyWordSet = readSensitiveWordFile(); 38 | //将敏感词库加入到HashMap中 39 | addSensitiveWordToHashMap(keyWordSet); 40 | } catch (Exception e) { 41 | e.printStackTrace(); 42 | } 43 | return sensitiveWordMap; 44 | } 45 | 46 | /** 47 | * 读取敏感词库,将敏感词放入HashSet中,构建一个DFA算法模型:
48 | * 中 = { 49 | * isEnd = 0 50 | * 国 = {
51 | * isEnd = 1 52 | * 人 = {isEnd = 0 53 | * 民 = {isEnd = 1} 54 | * } 55 | * 男 = { 56 | * isEnd = 0 57 | * 人 = { 58 | * isEnd = 1 59 | * } 60 | * } 61 | * } 62 | * } 63 | * 五 = { 64 | * isEnd = 0 65 | * 星 = { 66 | * isEnd = 0 67 | * 红 = { 68 | * isEnd = 0 69 | * 旗 = { 70 | * isEnd = 1 71 | * } 72 | * } 73 | * } 74 | * } 75 | * @author chenssy 76 | * @date 2014年4月20日 下午3:04:20 77 | * @param keyWordSet 敏感词库 78 | * @version 1.0 79 | */ 80 | @SuppressWarnings({ "rawtypes", "unchecked" }) 81 | private void addSensitiveWordToHashMap(Set keyWordSet) { 82 | sensitiveWordMap = new HashMap(keyWordSet.size()); //初始化敏感词容器,减少扩容操作 83 | String key = null; 84 | Map nowMap = null; 85 | Map newWorMap = null; 86 | //迭代keyWordSet 87 | Iterator iterator = keyWordSet.iterator(); 88 | while(iterator.hasNext()){ 89 | key = iterator.next(); //关键字 90 | nowMap = sensitiveWordMap; 91 | for(int i = 0 ; i < key.length() ; i++){ 92 | char keyChar = key.charAt(i); //转换成char型 93 | Object wordMap = nowMap.get(keyChar); //获取 94 | 95 | if(wordMap != null){ //如果存在该key,直接赋值 96 | nowMap = (Map) wordMap; 97 | } 98 | else{ //不存在则,则构建一个map,同时将isEnd设置为0,因为他不是最后一个 99 | newWorMap = new HashMap(); 100 | newWorMap.put("isEnd", "0"); //不是最后一个 101 | nowMap.put(keyChar, newWorMap); 102 | nowMap = newWorMap; 103 | } 104 | 105 | if(i == key.length() - 1){ 106 | nowMap.put("isEnd", "1"); //最后一个 107 | } 108 | } 109 | } 110 | } 111 | 112 | /** 113 | * 读取敏感词库中的内容,将内容添加到set集合中 114 | * @author chenssy 115 | * @date 2014年4月20日 下午2:31:18 116 | * @return 117 | * @version 1.0 118 | * @throws Exception 119 | */ 120 | @SuppressWarnings("resource") 121 | private Set readSensitiveWordFile() throws Exception{ 122 | Set set = null; 123 | 124 | File file = new File("D:\\SensitiveWord.txt"); //读取文件 125 | InputStreamReader read = new InputStreamReader(new FileInputStream(file),ENCODING); 126 | try { 127 | if(file.isFile() && file.exists()){ //文件流是否存在 128 | set = new HashSet(); 129 | BufferedReader bufferedReader = new BufferedReader(read); 130 | String txt = null; 131 | while((txt = bufferedReader.readLine()) != null){ //读取文件,将文件内容放入到set中 132 | set.add(txt); 133 | } 134 | } 135 | else{ //不存在抛出异常信息 136 | throw new Exception("敏感词库文件不存在"); 137 | } 138 | } catch (Exception e) { 139 | throw e; 140 | }finally{ 141 | read.close(); //关闭文件流 142 | } 143 | return set; 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /src/main/java/com/JUtils/sensitiveword/SensitivewordFilterUtil.java: -------------------------------------------------------------------------------- 1 | package com.JUtils.sensitiveword; 2 | 3 | import java.util.HashSet; 4 | import java.util.Iterator; 5 | import java.util.Map; 6 | import java.util.Set; 7 | 8 | /** 9 | * 铭感词过滤工具类 10 | * 11 | * @Author:chenssy 12 | * @date:2014年8月5日 13 | */ 14 | public class SensitivewordFilterUtil{ 15 | @SuppressWarnings("rawtypes") 16 | private Map sensitiveWordMap = null; 17 | public static int minMatchTYpe = 1; //最小匹配规则 18 | public static int maxMatchType = 2; //最大匹配规则 19 | 20 | /** 21 | * 构造函数,初始化敏感词库 22 | */ 23 | public SensitivewordFilterUtil(){ 24 | sensitiveWordMap = new SensitiveWordInit().initKeyWord(); 25 | } 26 | 27 | /** 28 | * 判断文字是否包含敏感字符 29 | * @author chenssy 30 | * @date 2014年4月20日 下午4:28:30 31 | * @param txt 文字 32 | * @param matchType 匹配规则 1:最小匹配规则,2:最大匹配规则 33 | * @return 若包含返回true,否则返回false 34 | * @version 1.0 35 | */ 36 | public boolean isContaintSensitiveWord(String txt,int matchType){ 37 | boolean flag = false; 38 | for(int i = 0 ; i < txt.length() ; i++){ 39 | int matchFlag = this.CheckSensitiveWord(txt, i, matchType); //判断是否包含敏感字符 40 | if(matchFlag > 0){ //大于0存在,返回true 41 | flag = true; 42 | } 43 | } 44 | return flag; 45 | } 46 | 47 | /** 48 | * 获取文字中的敏感词 49 | * @author chenssy 50 | * @date 2014年4月20日 下午5:10:52 51 | * @param txt 文字 52 | * @param matchType 匹配规则 1:最小匹配规则,2:最大匹配规则 53 | * @return 54 | * @version 1.0 55 | */ 56 | public Set getSensitiveWord(String txt , int matchType){ 57 | Set sensitiveWordList = new HashSet(); 58 | 59 | for(int i = 0 ; i < txt.length() ; i++){ 60 | int length = CheckSensitiveWord(txt, i, matchType); //判断是否包含敏感字符 61 | if(length > 0){ //存在,加入list中 62 | sensitiveWordList.add(txt.substring(i, i+length)); 63 | i = i + length - 1; //减1的原因,是因为for会自增 64 | } 65 | } 66 | 67 | return sensitiveWordList; 68 | } 69 | 70 | /** 71 | * 替换敏感字字符 72 | * @author chenssy 73 | * @date 2014年4月20日 下午5:12:07 74 | * @param txt 75 | * @param matchType 76 | * @param replaceChar 替换字符,默认* 77 | * @version 1.0 78 | */ 79 | public String replaceSensitiveWord(String txt,int matchType,String replaceChar){ 80 | String resultTxt = txt; 81 | Set set = getSensitiveWord(txt, matchType); //获取所有的敏感词 82 | Iterator iterator = set.iterator(); 83 | String word = null; 84 | String replaceString = null; 85 | while (iterator.hasNext()) { 86 | word = iterator.next(); 87 | replaceString = getReplaceChars(replaceChar, word.length()); 88 | resultTxt = resultTxt.replaceAll(word, replaceString); 89 | } 90 | 91 | return resultTxt; 92 | } 93 | 94 | /** 95 | * 获取替换字符串 96 | * @author chenssy 97 | * @date 2014年4月20日 下午5:21:19 98 | * @param replaceChar 99 | * @param length 100 | * @return 101 | * @version 1.0 102 | */ 103 | private String getReplaceChars(String replaceChar,int length){ 104 | String resultReplace = replaceChar; 105 | for(int i = 1 ; i < length ; i++){ 106 | resultReplace += replaceChar; 107 | } 108 | 109 | return resultReplace; 110 | } 111 | 112 | /** 113 | * 检查文字中是否包含敏感字符,检查规则如下:
114 | * @author chenssy 115 | * @date 2014年4月20日 下午4:31:03 116 | * @param txt 117 | * @param beginIndex 118 | * @param matchType 119 | * @return,如果存在,则返回敏感词字符的长度,不存在返回0 120 | * @version 1.0 121 | */ 122 | @SuppressWarnings({ "rawtypes"}) 123 | public int CheckSensitiveWord(String txt,int beginIndex,int matchType){ 124 | boolean flag = false; //敏感词结束标识位:用于敏感词只有1位的情况 125 | int matchFlag = 0; //匹配标识数默认为0 126 | char word = 0; 127 | Map nowMap = sensitiveWordMap; 128 | for(int i = beginIndex; i < txt.length() ; i++){ 129 | word = txt.charAt(i); 130 | nowMap = (Map) nowMap.get(word); //获取指定key 131 | if(nowMap != null){ //存在,则判断是否为最后一个 132 | matchFlag++; //找到相应key,匹配标识+1 133 | if("1".equals(nowMap.get("isEnd"))){ //如果为最后一个匹配规则,结束循环,返回匹配标识数 134 | flag = true; //结束标志位为true 135 | if(SensitivewordFilterUtil.minMatchTYpe == matchType){ //最小规则,直接返回,最大规则还需继续查找 136 | break; 137 | } 138 | } 139 | } 140 | else{ //不存在,直接返回 141 | break; 142 | } 143 | } 144 | if(matchFlag < 2 || !flag){ //长度必须大于等于1,为词 145 | matchFlag = 0; 146 | } 147 | return matchFlag; 148 | } 149 | } 150 | -------------------------------------------------------------------------------- /src/main/java/com/JUtils/sequence/GenerateSequenceUtil.java: -------------------------------------------------------------------------------- 1 | package com.JUtils.sequence; 2 | 3 | import java.text.DecimalFormat; 4 | import java.text.FieldPosition; 5 | import java.text.Format; 6 | import java.text.NumberFormat; 7 | import java.text.SimpleDateFormat; 8 | import java.util.Calendar; 9 | 10 | /** 11 | * 根据时间生成唯一序列ID
12 | * 时间精确到秒,ID最大值为99999且循环使用 13 | * 14 | * @Author:chenssy 15 | * @date:2016年4月17日 16 | */ 17 | public class GenerateSequenceUtil { 18 | private static final FieldPosition HELPER_POSITION = new FieldPosition(0); 19 | 20 | /** 时间:精确到秒 */ 21 | private final static Format dateFormat = new SimpleDateFormat("YYYYMMddHHmmss"); 22 | 23 | private final static NumberFormat numberFormat = new DecimalFormat("00000"); 24 | 25 | private static int seq = 0; 26 | 27 | private static final int MAX = 99999; 28 | 29 | public static synchronized String generateSequenceNo() { 30 | 31 | Calendar rightNow = Calendar.getInstance(); 32 | 33 | StringBuffer sb = new StringBuffer(); 34 | 35 | dateFormat.format(rightNow.getTime(), sb, HELPER_POSITION); 36 | 37 | numberFormat.format(seq, sb, HELPER_POSITION); 38 | 39 | if (seq == MAX) { 40 | seq = 0; 41 | } else { 42 | seq++; 43 | } 44 | 45 | return sb.toString(); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/JUtils/word/WordExportUtils.java: -------------------------------------------------------------------------------- 1 | package com.JUtils.word; 2 | 3 | import java.util.Vector; 4 | 5 | /** 6 | * @desc:word导入工具类
7 | * 需要对Word中的图片、样式、文字、表格进行处理,同时由于POI对Word的处理能力有限,所以采用Jadoc处理 8 | * 9 | * @Author:chenssy 10 | * @date:2014年8月10日 11 | */ 12 | public class WordExportUtils { 13 | Vector[] vector = new Vector[10]; 14 | 15 | String[] strings = new String[10]; 16 | } 17 | --------------------------------------------------------------------------------