Java: How can I read text and numbers from a file

后端 未结 3 860
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-12 02:24

I am creating a simple program to data read from a text file. The file stores information about a person, with the name, age and a number on each line:

Eg: File form

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-12 02:59

    I strongly suggest you use the Scanner class instead. That class provides you with methods such as nextInt and so on.

    You could use it to read from the file directly like this:

    Scanner s = new Scanner(new File("People.txt"));
    
    while (s.hasNext()) {
        people[i].addName(s.next());
        people[i].addBookNo(s.nextInt());
        people[i].addRating(s.nextInt());
    }
    

    (Just realized that you may have spaces in the name. That complicates things slightly, but I would still consider using a scanner.)

    An alternative solution would be to use a regular expression and groups to parse the parts. Something like this should do:

    (.*?)\s+(\d+)\s+(\d+)
    

提交回复
热议问题