简体   繁体   English

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

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

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 format per line 例如:每行的文件格式

      Francis Bacon  50    2

I can read in a file no problem if it is just text, but I am confused on how to differentiate between text and numbers. 如果只是文本,我可以读取文件没有问题,但是我对如何区分文本和数字感到困惑。 Here is a look at my code: 这是我的代码:

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++

        }

    }

}

I strongly suggest you use the Scanner class instead. 我强烈建议您改用Scanner类。 That class provides you with methods such as nextInt and so on. 该类为您提供了诸如nextInt类的方法。

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+)

The following regex works on these 3 cases, breaking them into 3 matched groups. 以下正则表达式适用于这3种情况,将它们分为3个匹配的组。

Regex (.*)\\s+(\\d+)\\s+(\\d+) 正则表达式(.*)\\s+(\\d+)\\s+(\\d+)

Cases 案例

Francis Bacon  50    2
Jill St. John 20 20
St. Francis Xavier III 3 3 

If you want to do in this way, you can try doing like this : 如果您想以这种方式做,可以尝试这样:

  1. Fixing the way data will be present in the file, say 修复数据在文件中的显示方式,例如

    firstName.lastName.age.number; firstName.lastName.age.number;

  2. Then you can write code to read data upto . 然后,您可以编写代码以读取数据。 and store it in a variable (you will be knowing what it is meant for) and after ";" 并将其存储在变量中(您将知道它的含义)并在“;”之后 there will be second entry. 将有第二个条目。

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

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