我只想阅读我需要阅读的部分。例如我的文本文件如下所示
Name Age Gender
=====================
Donald 13 Male
John 14 Non-binary
Pooh 42 Female
我只想读取数据,但我不知道如何读取,因为我的代码逐行读取 .txt 文件
try {
File myObj = new File("database.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) { //to read each line of the file
String data = myReader.nextLine();
String [] array = data.split(" "); //store the words in the file line by line
if(array.length ==5){ // to check if data has all five parameter
people.add(new Person(array[0], array[1],array[2], Double.parseDouble(array[3]), Double.parseDouble(array[4])));
}
}
JOptionPane.showMessageDialog(null, "Successfully Read File","Javank",JOptionPane.INFORMATION_MESSAGE);
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
最佳答案
您只需在进入循环之前调用 myReader.nextLine()
两次即可忽略前两行。
您可以采取的另一种方法是使用 RandomAccessFile
对象而不是 Scanner
来处理您的输入。如果您知道相关数据开始之前文件中有多少个字符,则可以使用 RandomAccessFile
对象的 seek
方法跳到输入的开头,例如如果文件中的数据之前有 50 个字符,您可以使用 randomAccessFile.seek(50)
,然后使用 randomAccessFile.readLine()
读取行。
我可能会建议使用第一种跳过两行的方法,因为它看起来更简单、更健壮。
关于java - 如何用java读取txt文件的某些行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61221898/