[英]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.