如何在Java中读取txt文件的某些行?

问题描述 投票:0回答:1

我只想阅读我需要的部分。例如我的文本文件看起来像这些

Name     Age   Gender
=====================
Donald    13    Male
John      14    Gay
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();
        }
java file file-handling readfile
1个回答
0
投票

进入循环之前,您可以简单地调用两次myReader.nextLine()来忽略前两行。

[您可以采用的另一种方法是使用RandomAccessFile对象而不是Scanner处理您的输入。如果您知道在相关数据开始之前文件中有多少个字符,则可以使用RandomAccessFile对象的seek方法跳至输入的开头,例如如果文件中的数据前有50个字符,则可以使用randomAccessFile.seek(50),然后使用randomAccessFile.readLine()读取各行。

我可能会建议使用第一种跳过两行的方法,因为它看起来更简单且健壮。

© www.soinside.com 2019 - 2024. All rights reserved.