public static void readTxtFile(String filePath, String key){
try {
String encoding="GBK";
File file=new File(filePath);
if(file.isFile() && file.exists()){ //判断文件是否存在
InputStreamReader read = new InputStreamReader(
new FileInputStream(file),encoding);//考虑到编码格式
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;
while((lineTxt = bufferedReader.readLine()) != null){
System.out.println(lineTxt.indexOf(key));
}
read.close();
}else{
System.out.println("找不到指定的文件");
}
} catch (Exception e) {
System.out.println("读取文件内容出错");
e.printStackTrace();
}
追问
如果我要找的是这样的一行数据,关键字是开头那一组数字,我要把这一行的所有信息都输出的话应该怎么弄?
追答读取txt方法依旧,获取数据的方法如下:
String str = "120 LiuHua Zhang 15451545"+ "\r\n" +"110 GEGE OET 1154155" +"\r\n" + "110 GEGE OET 1154155" +"\r\n";
System.out.println("原始字符串为: \n" + str);
// 比如你想获取所有以110开头的行数据
String[] myStr = str.split("110");
for(int i = 0;i < myStr.length; i++){
if(i < myStr.length - 1)
System.out.println(myStr[i + 1]);
}