java實現身份證號碼驗證的示例代碼
更新時間:2023年09月07日 14:11:43 作者:派大星`
這篇文章主要為大家詳細介紹了如何利用java語言實現身份證號碼驗證的功能,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下
需要編號文件
編號文件部分內容如下
11:北京市
1101:市轄區(qū)
110101:東城區(qū)
110102:西城區(qū)
110105:朝陽區(qū)
110106:豐臺區(qū)
110107:石景山區(qū)
110108:海淀區(qū)
......
java代碼如下
import java.io.*; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; import java.util.function.Consumer; import java.util.regex.Pattern; public class IdCardCheckUtils { public static final Integer[] idCardWeight = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};//身份證前17位數字依次乘以對應的權重因子 public static final String[] CONSTELLATION_ARR = {"水瓶座", "雙魚座", "白羊座", "金牛座", "雙子座", "巨蟹座", "獅子座", "處女座", "天秤座", "天蝎座", "射手座", "魔羯座"};//星座數組 public static final int[] CONSTELLATION_EDGE_DAY = {20, 19, 21, 21, 21, 22, 23, 23, 23, 23, 22, 22};//星座對應的邊緣日期 public static final String[] ZODIAC_ARR = {"猴", "雞", "狗", "豬", "鼠", "牛", "虎", "兔", "龍", "蛇", "馬", "羊"};//生肖 public static Map<Integer, String> idCardMap = new HashMap<>();//組裝根據余數,對應一個指定的校驗碼 private static Map<Integer, String> nativePlaceCode = new HashMap<>(4096, 1);//內存籍貫編號,記錄身份證編號對應的地址 public static void main(String[] args) throws Exception { String path = "C:\\Users\\Administrator\\Desktop\\code.txt";//編號文件 init(path);//初始化身份證校驗參數 String idCard = "512926164805034455";//測試的身份證號碼 checkIdCard(idCard);//校驗身份證是否輸入正常 //基本信息 System.out.println("出生日期:" + idCard.substring(6, 10) + "." + idCard.substring(10, 12) + "." + idCard.substring(12, 14)); System.out.println("性別:" +getSex(idCard)); System.out.println("年齡:" + getAge(idCard)); System.out.println("您的星座:" + getConstellation(idCard)); System.out.println("您的生肖:" + getAnimalSign(idCard)); //籍貫信息 int nativePlaceCode = Integer.parseInt(idCard.substring(0, 6));//籍貫組合編碼 int provinceCode = nativePlaceCode / 10000;//省編碼 int cityCode = nativePlaceCode / 100;//市編碼 int countyCode = nativePlaceCode;//縣編碼 System.out.println(IdCardCheckUtils.nativePlaceCode.get(provinceCode)); System.out.println(IdCardCheckUtils.nativePlaceCode.get(cityCode)); System.out.println(IdCardCheckUtils.nativePlaceCode.get(countyCode)); } /** * 初始化地區(qū)編碼文件與校驗碼 * * @param path * @throws IOException */ private static void init(String path) throws IOException { synchronized (String.class) { if (!idCardMap.isEmpty()) return; Consumer<String> function = line -> { String[] split = line.split(":"); nativePlaceCode.put(Integer.valueOf(split[0]), split[1]); }; read(path, function);//將文件內容加載到map內存中 final String[] idCardCheck = {"1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"};//身份證最后一位對應的校驗碼 for (int i = 0; i < 10; i++) { idCardMap.put(i, idCardCheck[i]);//校驗碼記錄 } } } /** * 驗證身份證號碼是否正常 * * @param idCardNo * @return */ public static void checkIdCard(String idCardNo) throws Exception { String idCard = idCardNo.toUpperCase();//將其轉成大寫有的身份證最后一位是字母 if (idCardNo.length() == 15) {//15位身份證轉成18位 if (!(idCardNo.matches("[0-9]{17}[0-9|x]|[0-9]{15}"))) throw new Exception("身份證號碼輸入錯誤,請輸入正確格式的15位身份證號碼"); String s2 = idCardNo.substring(0, 6);//15位轉換為18位 String s3 = idCardNo.substring(6, 15); String changed = s2.concat("19").concat(s3); idCard = changed.toUpperCase(); } if (!Pattern.matches("^\\d{17}", idCard.substring(0, 17))) throw new Exception("身份證號碼輸入錯誤,前17位必須是數字");//驗證身份證前17位是否為數字 char[] idCardCharNumber = idCard.toCharArray(); Integer resultSum = 0; for (int i = 0; i < idCardCharNumber.length - 1; i++) resultSum += Character.getNumericValue(idCardCharNumber[i]) * idCardWeight[i]; Integer lastResult = resultSum % 11;//將相加的前17位數字依次乘以對應的權重因子相加,相加的結果除以11,得到余數 //根據余數,對應一個指定的校驗碼。最終得到的校驗碼就是身份證號碼的最后一位數字。通過這個校驗碼,可以驗證前面17位數字是否正確,從而提高身份證號碼的準確性 if (!(idCardMap.containsKey(lastResult)) || !(idCardMap.get(lastResult).equals(idCard.substring(idCard.length() - 1)))) throw new Exception("身份證號碼校驗異常,輸入錯誤"); } /** * 根據日期獲取當前年齡 * * @return */ public static int getAge(String idCard) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd"); String dateString = dateFormat.format(new Date()); int currentDate = Integer.parseInt(dateString); int idCardDate = Integer.parseInt(idCard.substring(6, 10) + idCard.substring(10, 12) + idCard.substring(12, 14)); int age = (currentDate - idCardDate) / 10000; return age; } /** * 根據身份證id獲取當前年齡 * * @return */ public static String getSex(String idCard) { String sex = Integer.parseInt(idCard.substring(16, 17)) % 2 == 0 ? "女" : "男"; return sex; } /** * 根據身份證號判斷用戶星座 * * @param cardNo * @return */ public static String getConstellation(String cardNo) { String birthday = cardNo.substring(6, 14);// 獲取出生日期 Date birthdate = null; try { birthdate = new SimpleDateFormat("yyyyMMdd").parse(birthday); if (birthdate == null) return ""; Calendar cal = Calendar.getInstance(); cal.setTime(birthdate); int month = cal.get(Calendar.MONTH); int day = cal.get(Calendar.DAY_OF_MONTH); if (day < CONSTELLATION_EDGE_DAY[month]) month = month - 1; if (month >= 0) return CONSTELLATION_ARR[month]; return CONSTELLATION_ARR[11];// default to return 魔羯 } catch (ParseException e) { e.printStackTrace(); } return null; } /** * 根據身份證號判斷用戶生肖 * * @param cardNo * @return */ public static String getAnimalSign(String cardNo) { String birthday = cardNo.substring(6, 14);// 獲取出生日期 Date birthdate; try { birthdate = new SimpleDateFormat("yyyyMMdd").parse(birthday); Calendar cal = Calendar.getInstance(); cal.setTime(birthdate); return ZODIAC_ARR[cal.get(Calendar.YEAR) % 12]; } catch (ParseException e) { e.printStackTrace(); } return null; } public static void read(String path, Consumer<String> func) throws IOException { File file = new File(path); FileInputStream fileInputStream = null; InputStreamReader read = null;//考慮到編碼格式 BufferedReader bufferedReader = null; try { fileInputStream = new FileInputStream(file); read = new InputStreamReader(fileInputStream, "UTF-8"); bufferedReader = new BufferedReader(read); String lineTxt; while ((lineTxt = bufferedReader.readLine()) != null) func.accept(lineTxt);//讀取一行 } catch (IOException e) { e.printStackTrace(); } finally { bufferedReader.close(); read.close(); fileInputStream.close(); } } }
運行結果 ,身份證是隨意編寫的,可以用自己的身份證進行測試
到此這篇關于java實現身份證號碼驗證的示例代碼的文章就介紹到這了,更多相關java身份證號驗證內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
關于java.io.EOFException產生的原因以及解決方案
文章總結:EOFException異常通常發(fā)生在嘗試從空的ObjectInputStream對象中讀取數據時,解決方法是在finally語句中添加判斷,確保objectInputStream不為空后再進行關閉操作,在處理1.txt文件為空的情況時,捕獲EOFException可以避免程序終止,并且不會拋出空指針異常2025-01-01SpringCloud實戰(zhàn)小貼士之Zuul的路徑匹配
這篇文章主要介紹了SpringCloud實戰(zhàn)小貼士之Zuul的路徑匹配,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-10-10淺談Spring框架中@Autowired和@Resource的區(qū)別
最近review別人代碼的時候,看到了一些@Autowired不一樣的用法,覺得有些意思,下面這篇文章主要給大家介紹了關于Spring框架中@Autowired和@Resource區(qū)別的相關資料,需要的朋友可以參考下2022-10-10