简体   繁体   English

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

[英]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我只想读取数据但我不知道如何,因为我的代码逐行读取 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();
        }

You can simply call myReader.nextLine() twice before entering your loop to ignore the first two lines.在进入循环之前,您可以简单地调用myReader.nextLine()两次以忽略前两行。

Another approach you can take is to use a RandomAccessFile object instead of a Scanner to process your input.您可以采取的另一种方法是使用RandomAccessFile object 而不是Scanner来处理您的输入。 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() .如果您知道相关数据开始之前文件中有多少个字符,则可以使用RandomAccessFile对象的seek方法跳到输入的开头,例如,如果文件中有 50 个字符在您的数据之前可以使用randomAccessFile.seek(50)然后用randomAccessFile.readLine()读取行。

I would probably recommend using the first method of skipping 2 lines however because it seems more simple and robust.我可能会推荐使用第一种跳过 2 行的方法,因为它看起来更简单和健壮。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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