java——15位身份證號碼升級到18位
阿新 • • 發佈:2019-02-06
題目
完整程式碼:
package IDCard;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
/*
* 身份證升位規則:
第一代身份證十五位數升為第二代身份證十八位數的一般規則是:
第一步,在原十五位數身份證的第六位數後面插入19 ,這樣身份證號碼即為十七位數;
第二步,按照國家規定的統一公式計算出第十八位數,作為校驗碼放在第二代身份證的尾號。
驗碼計算方法:將身份證前十七位數分別乘以不同係數,
從第一至十七位的係數分別為7、9、10、5、8、4、2、1、6、3、7、9、10、5、8、4、2,
將這十七位數字和係數相乘的結果相加,用加出來的和除以11,看看餘數是多少。
餘數只可能有0、1、2、3、4、5、6、7、8、9、10這十一個數字,
其分別對應的最後一位身份證的號碼為1、0、X、9、8、7、6、5、4、3、2,
這樣就得出了第二代身份證第十八位數的校驗碼。
*/
public class Ic {
// 主要計算方法,identifyCard是傳入的15位身份證號
public static String get18Ic(String identifyCard) {
String retId = "";
String id17 = "";
int sum = 0;
int y = 0;
// 定義陣列加權因子
int[] wf = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
// 定義陣列存放校驗碼
String[] cc = { "1", "0", "x", "9", "8", "7", "6", "5", "4", "3", "2" };
// 在原15位數身份證的第六位數後面插入19
id17 = identifyCard.substring(0, 6) + "19" + identifyCard.substring(6);
// 17位數字和係數相乘,結果相加
for (int i = 0; i < 17; i++) {
sum = sum + Integer.valueOf(id17.substring(i, i + 1 )) * wf[i];
}
// 計算餘數
y = sum % 11;
// 通過模獲得對應的校驗碼cc[yy];
retId = id17 + cc[y];
return retId;
}
// 讀取檔案,引數fileName為傳入的要讀取檔案的路徑及檔名
public static void readFileByLines(String fileName) {
File file = new File(fileName);
BufferedReader reader = null;
try {
reader=new BufferedReader(new FileReader(file));
String tempString=null;
int line=1;
//一次讀取一行
while((tempString=reader.readLine())!=null){
//新的身份證號碼
String returnId=get18Ic(tempString);
//寫入到檔案中
WriterFile(returnId);
line++;
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
}
//存入檔案的名稱
static String file=null;
//引數returnID為返回的18位身份證號,是要寫入檔案的內容
public static void WriterFile(String returnID){
FileWriter fw = null ;
//如果檔案不存在,建立檔案
try {
File f=new File(file);
fw=new FileWriter(f,true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
PrintWriter pw=new PrintWriter(fw);
pw.println(returnID+"\n");
pw.flush();
try {
fw.flush();
pw.close();
fw.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
//以日期作為輸出檔案的檔名
public static String FileName(){
SimpleDateFormat simpleDateFormat;
simpleDateFormat =new SimpleDateFormat("yyyyMMddHHmmss");
Date date=new Date();
String filenametxt=simpleDateFormat.format(date);
return filenametxt;
}
public static void main(String[] args) {
file="C:\\Users\\李強\\Desktop\\IDCardNo("+FileName()+").txt";//寫入檔案的名稱,及路徑
System.out.println("正在讀取檔案,轉換中");
readFileByLines("C:\\Users\\李強\\Desktop\\15.txt");//讀取檔案的路徑,及檔名
System.out.println("轉換完成!");
}
}