从文件中打印特定字符串行的最佳方法是什么?
例如: file.txt的
Id : 123
car : toyota
model : 1998
Id : 129
car : merecdes
model :2007
在控制台: 输入ID以搜索特定的汽车和型号: 123
ID:123 汽车:丰田 型号:1998
代码: / *跳过代码的“写文件”部分* / 试图实施:“根据示例
读取id并打印汽车和名称”File mfile = new File("Employee.txt");
Scanner scan = new Scanner(mfile);
int firstline=0; //
String thisLine = null;
LineNumberReader m = new LineNumberReader(new FileReader(mfile));
// LineNumberReader lnr = new LineNumberReader(new FileReader(new File("Employee")));
BufferedReader br = new BufferedReader(m);
while(scan.hasNextLine()){
/* myEmployee.getID();
myEmployee.getName();
myEmployee.getAge();
*/
String line = scan.nextLine();// check next line
String s = null;
firstline++;
if(firstline==1)
{
System.out.println(line);
String line2 = scan.nextLine();
firstline++;
if(s== "Name"){
System.out.println(line2);
}
}
}
scan.close();
答案 0 :(得分:0)
伪代码://代码不言自明。
while(EOF) {
String data = readLine();
if(data.contains(inputId)) {
//here record gets started
System.out.println(data);
String recordData;
while((recordData = readLine()) != '\n'){
System.out.println(recordData)
}
break;
}
}
答案 1 :(得分:0)
您必须先检索该行。然后使用 split()方法,您可以获得所需的内容。
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Read {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("someFile"));
try {
String line = br.readLine();
while (line != null) {
if(line.contains("String 1")) {
// ...
} else if (line.contains("String 2")) {
// ...
}
line = br.readLine();
String[] columns = line.split(" ");
System.out.println("ID: "+ columns[0] );
System.out.println("Car : "+ columns[1] );
System.out.println("Model : "+ columns[2] );
}
} finally {
br.close();
}
}
}
答案 2 :(得分:0)
首先,我可以知道文件格式是否可以更改?如果记录存储如下所有内容将变得简单: 身份证,汽车,模型 123,丰田,1988年 129,merecdes,2007年 如果没有,那么忽略这一点......
我认为您可以使用HashMap通过每4行读取来存储汽车信息,然后您可以通过HashMap.get(Id)获得一辆汽车。