Java:如何从文件中读取文本和数字

Bod*_*yte 2 java file input

我正在创建一个简单的程序来从文本文件中读取数据.该文件存储有关人员的信息,每行包含姓名,年龄和编号:

例如:每行的文件格式

      Francis Bacon  50    2
Run Code Online (Sandbox Code Playgroud)

如果它只是文本,我可以在文件中读取没有问题,但我对如何区分文本和数字感到困惑.这是我的代码:

import java.io.*;


public class Test{

    private People people[] = new People[5];


    public Test(){
        BufferedReader input;

        input = new BufferedReader(new FileReader("People.txt"));// file to be readfrom
        String fileLine;
        int i = 0;

        while (test != null){
            fileLine = input.readLine(); 

            // Confused as to how to parse this line into seperate parts and store in object:
            // eg:
            people[i].addName(fileLine - part 1);
            people[i].addBookNo(fileLine - part 2);
            people[i].addRating(fileLine - part 3)

            i++

        }

    }

}
Run Code Online (Sandbox Code Playgroud)

aio*_*obe 5

我强烈建议你改用这Scanner门课.该类为您提供诸如此类的方法nextInt.

您可以使用它直接读取文件,如下所示:

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());
}
Run Code Online (Sandbox Code Playgroud)

(刚才意识到你的名字可能有空格.这会让事情变得复杂,但我仍然会考虑使用扫描仪.)

另一种解决方案是使用正则表达式和组来解析部分.这样的事情应该做:

(.*?)\s+(\d+)\s+(\d+)
Run Code Online (Sandbox Code Playgroud)