工具类

工具类

1 前言

简单的几个工具类

2 工具类

1.Excel导入导出工具类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
package com.empl.mgr.utils;

import com.empl.mgr.dto.EmployeesBasicInfoDto;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
* @author fenghao
* @Title: ExcelUtil
* @Description: Excel工具类
* @date 2020/05/0717:30
*/
public class ExcelUtil {

/**
* Excel表格导出
* @param excelData Excel表格的数据,封装为List<List<String>>
* @param sheetName sheet的名字
* @param fileName 导出Excel的文件名
* @throws Exception 抛异常
*/
public static void exportReportExcel(HttpServletResponse response,List<List<String>> excelData,
String sheetName, String fileName) throws Exception {

//声明一个工作簿
HSSFWorkbook workbook = new HSSFWorkbook();

//生成一个表格,设置表格名称
HSSFSheet sheet = workbook.createSheet(sheetName);
sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, 0));
sheet.addMergedRegion(new CellRangeAddress(0, 0, 1, 4));
sheet.addMergedRegion(new CellRangeAddress(0, 0, 5, 8));
sheet.addMergedRegion(new CellRangeAddress(0, 0, 9, 11));
sheet.addMergedRegion(new CellRangeAddress(0, 0, 12, 14));
sheet.addMergedRegion(new CellRangeAddress(0, 0, 15, 17));
sheet.addMergedRegion(new CellRangeAddress(0, 0, 18, 22));
sheet.addMergedRegion(new CellRangeAddress(0, 0, 23, 24));
//设置表格列宽度
sheet.setDefaultColumnWidth(12);
sheet.setDefaultRowHeightInPoints(18);

CellStyle style = workbook.createCellStyle();
// 设置样式
style.setFillForegroundColor(IndexedColors.PALE_BLUE.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
style.setBorderBottom(BorderStyle.THIN);
style.setBorderLeft(BorderStyle.THIN);
style.setBorderRight(BorderStyle.THIN);
style.setBorderTop(BorderStyle.THIN);
style.setAlignment(HorizontalAlignment.CENTER);
style.setVerticalAlignment(VerticalAlignment.CENTER);
// 生成一个字体
Font font = workbook.createFont();
font.setColor(IndexedColors.BLACK.getIndex());
font.setFontHeightInPoints((short) 10);
font.setBold(true);
// 把字体应用到当前的样式
style.setFont(font);
// 生成并设置第二个样式
CellStyle style2 = workbook.createCellStyle();
style2.setFillForegroundColor(IndexedColors.WHITE.getIndex());
style2.setFillPattern(FillPatternType.SOLID_FOREGROUND);
style2.setBorderBottom(BorderStyle.THIN);
style2.setBorderLeft(BorderStyle.THIN);
style2.setBorderRight(BorderStyle.THIN);
style2.setBorderTop(BorderStyle.THIN);
style2.setAlignment(HorizontalAlignment.CENTER);
style2.setVerticalAlignment(VerticalAlignment.CENTER);
// 生成第二种字体
Font font2 = workbook.createFont();
font2.setFontHeightInPoints((short) 8);
// 把字体应用到当前的样式
style2.setFont(font2);
// 生成并设置第三个样式
CellStyle style3 = workbook.createCellStyle();
style3.setFillForegroundColor(IndexedColors.CORAL.getIndex());
style3.setFillPattern(FillPatternType.SOLID_FOREGROUND);
style3.setBorderBottom(BorderStyle.THIN);
style3.setBorderLeft(BorderStyle.THIN);
style3.setBorderRight(BorderStyle.THIN);
style3.setBorderTop(BorderStyle.THIN);
style3.setAlignment(HorizontalAlignment.CENTER);
style3.setVerticalAlignment(VerticalAlignment.CENTER);
// 生成第三种字体
Font font3 = workbook.createFont();
font3.setColor(IndexedColors.RED.getIndex());
font3.setFontHeightInPoints((short) 9);
// 把字体应用到当前的样式
style3.setFont(font3);
//写入List<List<String>>中的数据
int rowIndex = 0;
for(List<String> data : excelData){
//创建一个row行,然后自增1
HSSFRow row = sheet.createRow(rowIndex++);
//遍历添加本行数据
for (int i = 0; i < data.size(); i++) {
//创建一个单元格
HSSFCell cell = row.createCell(i);
if(rowIndex == 1 || rowIndex == 2){
cell.setCellStyle(style);
} else if(rowIndex == excelData.size()) {
cell.setCellStyle(style3);
} else {
cell.setCellStyle(style2);
}
//创建一个内容对象
HSSFRichTextString text = new HSSFRichTextString(data.get(i));
//将内容对象的文字内容写入到单元格中
cell.setCellValue(text);
}
}
//输出流
OutputStream output = response.getOutputStream();
response.setContentType("application/vnd.ms-excel");
fileName = URLEncoder.encode(fileName, "UTF-8");
//设置导出Excel的名称
response.setHeader("Content-disposition", "attachment;filename=" + fileName);
/*FileOutputStream output = new FileOutputStream( "D:\\"+fileName);*/
//workbook将Excel写入到response的输出流中,供页面下载该Excel文件
workbook.write(output);
output.close();
//关闭workbook
workbook.close();
}

/**
* Excel表格导出
* @param response HttpServletResponse对象
* @param excelData Excel表格的数据,封装为List<List<String>>
* @param sheetName sheet的名字
* @param fileName 导出Excel的文件名
* @throws Exception 抛异常
*/
public static void exportExcel(HttpServletResponse response,
List<List<String>> excelData,
String sheetName,
String fileName) throws Exception {

//声明一个工作簿
HSSFWorkbook workbook = new HSSFWorkbook();

//生成一个表格,设置表格名称
HSSFSheet sheet = workbook.createSheet(sheetName);
//设置表格列宽度
sheet.setDefaultColumnWidth(18);
sheet.setDefaultRowHeightInPoints(22);

CellStyle style = style(workbook);
// 生成并设置另一个样式 内容的背景
CellStyle style2 = style2(workbook,0);
//写入List<List<String>>中的数据
int rowIndex = 0;
for(List<String> data : excelData){
//创建一个row行,然后自增1
HSSFRow row = sheet.createRow(rowIndex++);
//遍历添加本行数据
for (int i = 0; i < data.size(); i++) {
//创建一个单元格
HSSFCell cell = row.createCell(i);
if(rowIndex == 1){
cell.setCellStyle(style);
} else {
cell.setCellStyle(style2);
}
//创建一个内容对象
HSSFRichTextString text = new HSSFRichTextString(data.get(i));
//将内容对象的文字内容写入到单元格中
cell.setCellValue(text);
}
}
//输出流
OutputStream output = response.getOutputStream();
response.setContentType("application/vnd.ms-excel");
fileName = URLEncoder.encode(fileName, "UTF-8");
//设置导出Excel的名称
response.setHeader("Content-disposition", "attachment;filename=" + fileName);
/*FileOutputStream output = new FileOutputStream( "D:\\"+fileName);*/
//workbook将Excel写入到response的输出流中,供页面下载该Excel文件
workbook.write(output);
output.close();
//关闭workbook
workbook.close();
}

public static CellStyle style2(HSSFWorkbook workbook,int type){
CellStyle style2 = workbook.createCellStyle();
style2.setFillForegroundColor(IndexedColors.WHITE.getIndex());
style2.setFillPattern(FillPatternType.SOLID_FOREGROUND);
style2.setBorderBottom(BorderStyle.THIN);
style2.setBorderLeft(BorderStyle.THIN);
style2.setBorderRight(BorderStyle.THIN);
style2.setBorderTop(BorderStyle.THIN);
style2.setAlignment(HorizontalAlignment.CENTER);
style2.setVerticalAlignment(VerticalAlignment.CENTER);
// 生成另一个字体
Font font2 = workbook.createFont();
if(type == 1){
font2.setColor(IndexedColors.RED.getIndex());
}
font2.setFontHeightInPoints((short) 10);
// 把字体应用到当前的样式
style2.setFont(font2);
return style2;
}

public static CellStyle style(HSSFWorkbook wb){
CellStyle style = wb.createCellStyle();
// 设置样式
style.setFillForegroundColor(IndexedColors.GOLD.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
style.setBorderBottom(BorderStyle.THIN);
style.setBorderLeft(BorderStyle.THIN);
style.setBorderRight(BorderStyle.THIN);
style.setBorderTop(BorderStyle.THIN);
style.setAlignment(HorizontalAlignment.CENTER);
style.setVerticalAlignment(VerticalAlignment.CENTER);
// 生成一个字体
Font font = wb.createFont();
font.setColor(IndexedColors.BLACK.getIndex());
font.setFontHeightInPoints((short) 12);
font.setBold(true);
// 把字体应用到当前的样式
style.setFont(font);
return style;
}

public static String[][] getArrData(File file, int ignoreRows) throws IOException {
List<String[]> result = new ArrayList<String[]>();
int rowSize = 0;
BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
// 打开HSSFWorkbook
POIFSFileSystem fs = new POIFSFileSystem(in);
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFCell cell = null;
for (int sheetIndex = 0; sheetIndex < wb.getNumberOfSheets(); sheetIndex++) {
HSSFSheet st = wb.getSheetAt(0);
// 第一行为标题,不取
for (int rowIndex = ignoreRows; rowIndex <= st.getLastRowNum(); rowIndex++) {
HSSFRow row = st.getRow(rowIndex);
if (row == null) {
continue;
}
int tempRowSize = row.getLastCellNum();
if (tempRowSize > rowSize) {
rowSize = tempRowSize;
}
String[] values = new String[rowSize];
Arrays.fill(values, "");
boolean hasValue = false;
for (short columnIndex = 0; columnIndex < row.getLastCellNum(); columnIndex++) {
String value = "";
cell = row.getCell(columnIndex);
if (cell != null) {
// 注意:一定要设成这个,否则可能会出现乱码
// cell.setEncoding(HSSFCell.ENCODING_UTF_16);
switch (cell.getCellTypeEnum()) {
case STRING:
value = cell.getStringCellValue();
break;
case NUMERIC:
if (HSSFDateUtil.isCellDateFormatted(cell)) {
Date date = cell.getDateCellValue();
if (date != null) {
value = new SimpleDateFormat("yyyy-MM-dd")
.format(date);
} else {
value = "";
}
} else {
value = new DecimalFormat("0").format(cell
.getNumericCellValue());
}
break;
case FORMULA:
// 导入时如果为公式生成的数据则无值
if (!cell.getStringCellValue().equals("")) {
value = cell.getStringCellValue();
} else {
value = cell.getNumericCellValue() + "";
}
break;
case BLANK:
value = "";
break;
case ERROR:
value = "";
break;
case BOOLEAN:
value = (cell.getBooleanCellValue() == true ? "Y"
: "N");
break;
default:
value = "";
}
}
if (columnIndex == 0 && value.trim().equals("")) {
break;
}
values[columnIndex] = rightTrim(value);
hasValue = true;
}
if (hasValue) {
result.add(values);
}
}
}
in.close();
String[][] returnArray = new String[result.size()][rowSize];
for (int i = 0; i < returnArray.length; i++) {
returnArray[i] = (String[]) result.get(i);
}
return returnArray;
}

/**
* 去掉字符串右边的空格
*
* @param str 要处理的字符串
* @return 处理后的字符串
*/
public static String rightTrim(String str) {
if (str == null) {
return "";
}
int length = str.length();
for (int i = length - 1; i >= 0; i--) {
if (str.charAt(i) != 0x20) {
break;
}
length--;
}
return str.substring(0, length);
}
}

2.时间工具类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
package com.empl.mgr.utils;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import com.empl.mgr.constant.TimeFormatConstant;
import com.empl.mgr.dto.DateDto;
import org.apache.commons.lang.StringUtils;

public class DateTimeUtil {

/**
* @param:
* @description: 获取当前时间
* @return: java.util.Date
* @date: 2020/5/12
*/
public static Date getCurrentTime() {
return new Date();
}

/**
* @param: date
* @param: format
* @description: long转String
* @return: java.lang.String
* @date: 2020/5/12
*/
public static String conversionTime(long date, String format) {
if (CompareUtil.isEmpty(date) || StringUtils.isEmpty(format))
return "";
return new SimpleDateFormat(format).format(new Date(date));
}


/**
* @param: date
* @param: format
* @description: Date转String
* @return: java.lang.String
* @date: 2020/5/12
*/
public static String dateToString(Date date, String format) {
if (CompareUtil.isEmpty(date) || StringUtils.isEmpty(format))
return "";
return new SimpleDateFormat(format).format(date);
}


/**
* @param: date
* @param: format
* @description: String转Date
* @return: java.util.Date
* @date: 2020/5/12
*/
public static Date stringToDate(String date, String format) {
if (CompareUtil.isEmpty(date) || StringUtils.isEmpty(format))
return null;
Date time = null;
try {
time = new SimpleDateFormat(format).parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
return time;
}

/**
* @param: null
* @description: 司龄计算
* @return:
* @date: 2020/5/6
*/
public static float seniorityTime(String date) {
Date entryTime = stringToDate(date, TimeFormatConstant.YYYY_MM_DD);
Date nowTime = getCurrentTime();
long dayNum = nowTime.getTime() - entryTime.getTime();
float time = dayNum / 1000 / 60 / 60 / 24;
time = time / 365.5f;
float seniority = new BigDecimal(time).setScale(1, BigDecimal.ROUND_HALF_UP).floatValue();
return seniority;
}

/**
* @param: idcard
* @description: 根据身份证计算年龄
* @return: java.lang.Integer
* @date: 2020/5/8
*/
public static int idCardToAge(String idcard) {
int selectYear = Integer.valueOf(idcard.substring(6, 10)); //出生的年份
int selectMonth = Integer.valueOf(idcard.substring(10, 12)); //出生的月份
int selectDay = Integer.valueOf(idcard.substring(12, 14)); //出生的日期
Calendar cal = Calendar.getInstance();
int yearMinus = cal.get(Calendar.YEAR) - selectYear;
int monthMinus = cal.get(Calendar.MONTH) + 1 - selectMonth;
int dayMinus = cal.get(Calendar.DATE) - selectDay;
Integer age = yearMinus;
if (yearMinus < 0) {
age = 0;
} else if (yearMinus == 0) {
age = 0;
} else if (yearMinus > 0) {
if (monthMinus == 0) {
if (dayMinus < 0) {
age = age - 1;
}
} else if (monthMinus > 0) {
age = age + 1;
}
}
return age;
}

/**
* @param: date
* @param: months
* @description: 获取添加月份的日期
* @return: java.lang.String
* @date: 2020/5/12
*/
public static String getAddMonthDate(String date, int months) {
Date toDate = stringToDate(date, TimeFormatConstant.YYYY_MM_DD);
Calendar cal = Calendar.getInstance();
cal.setTime(toDate);
cal.add(Calendar.MONTH, months);
String temp = dateToString(cal.getTime(),TimeFormatConstant.YYYY_MM_DD);
return temp;
}

/**
* @param: date
* @param: days
* @description: 获取添加天数的日期
* @return: java.lang.String
* @date: 2020/5/12
*/
public static Date getAddDayDate(String date, int days) {
Date dayDate = stringToDate(date, TimeFormatConstant.YYYY_MM_DD);
Calendar cal = Calendar.getInstance();
cal.setTime(dayDate);
cal.add(Calendar.DATE, days);
return cal.getTime();
}

/**
* @param: date1
* @param: dateStr2
* @param: days
* @description: 时间比较
* @return: int
* @date: 2020/5/13
*/
public static int compareDate(Date date1, String dateStr2 ,int days) {
Date date2 = getAddDayDate(dateStr2, days);
if (date1.getTime() > date2.getTime()){
return -1;
}else if (date1.getTime() < date2.getTime()){
return 1;
}else{
return 0;
}

}

/**
* @param:
* @description: 间隔时间
* @return: java.util.Date
* @date: 2020/5/13
*/
public static DateDto getDate(int months){
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH)+1;
int day = cal.get(Calendar.DATE);
Integer[] daysArr = {31, (isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if(daysArr[month-1] > day){
cal.add(Calendar.DATE,0-day);
}
DateDto dto = new DateDto();
dto.setEndTime(dateToString(cal.getTime(),TimeFormatConstant.YYYY_MM_DD));
cal.add(Calendar.MONTH,0-months);
dto.setStartTime(dateToString(cal.getTime(),TimeFormatConstant.YYYY_MM_DD));
return dto;
}

/**
* @param: year
* @description: 判断是否是闰年
* @return: boolean
* @date: 2020/5/13
*/
public static boolean isLeapYear(int year){
if(year%4 == 0 && year%100!=0 || year%400 == 0){
return true;
}else{
return false;
}
}
}

3.格式校验

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
package com.empl.mgr.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
* @description: 校验
* @author: fenghao
* @date: 2020/5/19
**/
public class CheckUtil {

/**
* @param: phone
* @description: 手机号校验
* @return: boolean
* @date: 2020/5/19
*/
public static boolean checkPhone(String phone) {
String regex = "^((13[0-9])|(14[0-9])|(15([0-9]))|(16([0-9]))|(17([0-9]))|(18([0-9]))|(19([0-9])))\\d{8}$";
if (phone.length() != 11) {
return false;
} else {
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(phone);
boolean isMatch = m.matches();
return isMatch;
}
}

/**
* @param: email
* @description: 验证邮箱地址是否正确
* @return: boolean
* @date: 2020/5/19
*/
public static boolean checkEmail(String email){
boolean flag = false;
try{
String check = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
Pattern regex = Pattern.compile(check);
Matcher matcher = regex.matcher(email);
flag = matcher.matches();
}catch(Exception e){
flag = false;
}
return flag;
}

/**
* @param: IDNumber
* @description: 身份证号校验
* @return: boolean
* @date: 2020/5/19
*/
public static boolean checkIdentity(String IDNumber) {
if (IDNumber == null || "".equals(IDNumber)) {
return false;
}
// 定义判别用户身份证号的正则表达式(15位或者18位,最后一位可以为字母)
String regularExpression =
"(^[1-9]\\d{5}(18|19|20)\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$)|"
+ "(^[1-9]\\d{5}\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}$)";
boolean matches = IDNumber.matches(regularExpression);
// 判断第18位校验值
if (matches) {
if (IDNumber.length() == 18) {
try {
char[] charArray = IDNumber.toCharArray();
// 前十七位加权因子
int[] idCardWi = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
// 这是除以11后,可能产生的11位余数对应的验证码
String[] idCardY = {"1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"};
int sum = 0;
for (int i = 0; i < idCardWi.length; i++) {
int current = Integer.parseInt(String.valueOf(charArray[i]));
int count = current * idCardWi[i];
sum += count;
}
char idCardLast = charArray[17];
int idCardMod = sum % 11;
if (idCardY[idCardMod].toUpperCase()
.equals(String.valueOf(idCardLast).toUpperCase())) {
return true;
} else {
System.out.println("身份证最后一位:" + String.valueOf(idCardLast).toUpperCase()
+ "错误,正确的应该是:" + idCardY[idCardMod].toUpperCase());
return false;
}

} catch (Exception e) {
e.printStackTrace();
return false;
}
} else {
return false;
}
}
return matches;
}

/**
* @param: cardId
* @description: 校验银行卡卡号
* @return: boolean
* @date: 2020/5/27
*/
public static boolean checkBankCard(String cardId) {
String check = "^([1-9]{1})(\\d{15}|\\d{18})$";
Pattern regex = Pattern.compile(check);
Matcher matcher = regex.matcher(cardId);
if(!matcher.matches()){
return false;
}
char bit = getBankCardCheckCode(cardId.substring(0, cardId.length() - 1));
if(bit == 'N'){
return false;
}
return cardId.charAt(cardId.length() - 1) == bit;
}

/**
* @param: nonCheckCodeCardId
* @description: 从不含校验位的银行卡卡号采用 Luhm 校验算法获得校验位
* @return: char
* @date: 2020/5/27
*/
public static char getBankCardCheckCode(String nonCheckCodeCardId){
if(nonCheckCodeCardId == null || nonCheckCodeCardId.trim().length() == 0
|| !nonCheckCodeCardId.matches("\\d+")) {
//如果传的不是数据返回N
return 'N';
}
char[] chs = nonCheckCodeCardId.trim().toCharArray();
int luhmSum = 0;
for(int i = chs.length - 1, j = 0; i >= 0; i--, j++) {
int k = chs[i] - '0';
if(j % 2 == 0) {
k *= 2;
k = k / 10 + k % 10;
}
luhmSum += k;
}
return (luhmSum % 10 == 0) ? '0' : (char)((10 - luhmSum % 10) + '0');
}
}

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×