Gerome Tahud
Gerome Tahud

Reputation: 103

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

Upvotes: 0

Views: 356

Answers (1)

Apollo
Apollo

Reputation: 82

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, e.g. 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.

Upvotes: 1

Related Questions