Java - 使用扫描程序读取大文本文件

时间:2011-07-09 21:05:35

标签: java java.util.scanner

我有一个非常大的文本文件,其中包含客户信息。我想从文本文件中读取所有客户信息。

这就是我的文本文件的组织方式:

Costomer 1:
Name: 
Erik Andersson
Adress:
Street1
Phone number:
085610540

Costomer 2:
Name: 
Lars Larsson
Adress:
Street1
Phone number:
085610540

我希望能够阅读所有客户信息。它有什么好办法吗?我读过有关Scanner和Pattern的内容,并想知道在这种情况下使用它们是否是个好主意?我的文本文件非常大,包含数百个客户。

任何人都知道如何从文本文件中读取所有信息?我创建了一个客户变量的类,我只需要帮助读取文本文件。我想以有条理的方式阅读这些信息。

非常感谢所有帮助。

2 个答案:

答案 0 :(得分:1)

像这样:

public void getEmployees(File f) throws Exception {
    // An ArrayList of your Employee-Object to hold multiple Employees
    ArrayList<Employee> employees = new ArrayList<Employee>();
    // The reader to read from your File
    BufferedReader in = new BufferedReader(new FileReader(f.getAbsolutePath()));
    // This will later contain one single line from your file
    String line = "";

    // Temporary fields for the constructor of your Employee-class
    int number;
    String name;
    String adress;
    String phone;

    // Read the File untill the end is reached (when "readLine()" returns "null")
    // the "line"-String contains one single line from your file.
    while ( (line = in.readLine()) != null ) {
        // See if your Line contains the Customers ID:
        if (line.startsWith("Customer")) {
            // Parse the number to an "int" because the read value
            // is a String.
            number = Integer.parseInt(s.substring("Customer ".length()).substring(0,s.indexOf(':')));
        } else if (line.startsWith("Adress:")) {
            // The Adress is noted in the next line, so we
            // read the next line:
            adress = in.readLine();
        } else if (line.startsWith("Phone number:")) {
            // Same as the Adress:
            phone = in.readLine();
        } else if (line.startsWith("Name:")){
            // Same as the Adress:
            name = in.readLine();
        } else if ( line.equals("") ){
            // The empty line marks the end of one set of Data
            // Now we can create your Employee-Object with the
            // read values:
            employees.add(new Employee(number,name,adress,phone));      
        }
    }
    // After we processed the whole file, we return the Employee-Array
    Employee[] emplyeeArray = (Employee[])employees.toArray();
}

请给你+1并更正你的hw lol

答案 1 :(得分:1)

作为stas回答的一点延伸:

最初发布的代码不起作用,因为continue会跳过当前的循环迭代。因此,除非该行以""开头,否则什么都没做。但是没有为我投票,因为你有正确的想法。

我更新了代码(没有测试它),现在应该可以使用了。

如果您发布代码来回答问题,您应该对其进行评论,以便读者能够理解它的作用。

此外,不要求声誉,这只是不礼貌。

相关问题