[英]How to read certain lines of a txt file in java?
我只想阅读我需要的部分。 例如我的文本文件看起来像这些
Name Age Gender
=====================
Donald 13 Male
John 14 Non-binary
Pooh 42 Female
我只想读取数据但我不知道如何,因为我的代码逐行读取 a.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
object 而不是Scanner
来处理您的输入。 如果您知道相关数据开始之前文件中有多少个字符,则可以使用RandomAccessFile
对象的seek
方法跳到输入的开头,例如,如果文件中有 50 个字符在您的数据之前可以使用randomAccessFile.seek(50)
然后用randomAccessFile.readLine()
读取行。
我可能会推荐使用第一种跳过 2 行的方法,因为它看起来更简单和健壮。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.