楼主大一,Java小白,课程设计遇到的问题,用io流读取txt中的数据,查询时输入身份证号,要求显示出这个身份证号所在的这一行信息,这个要怎么做呢?
可以使用BuffferedReader来读取文件,并一行一行的比较,如果该行包含这个身份证号,就返回该行的信息即可。比如你的txt为D:\data.txt
public static void main(String[] args) {
String idNum = "431127004";
String txtPath = "D:\\data.txt";
String result = getMatchLine(txtPath, idNum);
if (result == null) {
System.out.println("不存在身份证号为" + idNum + "的信息。");
} else {
System.out.println("查询成功,身份证号为" + idNum + "的信息如下:");
System.out.println(result);
}
}
private static String getMatchLine(String txtPath, String idNum) {
String result = null;
try {
FileReader fr = new FileReader(new File("D:\\data.txt"));
BufferedReader br = new BufferedReader(fr);
String line = br.readLine();
while (line != null) {
if (line.contains("")) {
result = line;
break;
} else {
line = br.readLine();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
文件不大,可以整体读入,用split按行分割装入List
然后循环遍历用indexof判断是否存在
把内容读取到一个字符串中,然后按照冒号分隔分组即可