#题目
#完整代码:
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("转换完成!");
}
}