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

时间:2020-04-15 05:27:48

标签: java file file-handling readfile

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

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();
        }

1 个答案:

答案 0 :(得分:1)

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

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

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