简体   繁体   中英

How to read certain lines of a txt file in java?

I want to read only the parts i need to. For example my text file look likes these

Name     Age   Gender
=====================
Donald    13    Male
John      14    Non-binary
Pooh      42    Female

I only want to read the data but i don't know how because my code reads a.txt file line by line

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

You can simply call myReader.nextLine() twice before entering your loop to ignore the first two lines.

Another approach you can take is to use a RandomAccessFile object instead of a Scanner to process your input. If you know how many characters are in the file before the beginning of your relevant data, you can use the RandomAccessFile object's seek method to skip to the beginning of your input, eg if there are 50 characters in the file before your data you can use randomAccessFile.seek(50) and then read the lines with randomAccessFile.readLine() .

I would probably recommend using the first method of skipping 2 lines however because it seems more simple and robust.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM