簡體   English   中英

Java - 使用掃描儀讀取大文本文件

[英]Java - Use Scanner to read big text files

我有一個非常大的包含客戶信息的文本文件。 我想從文本文件中讀取所有客戶信息。

這是我的文本文件的組織方式:

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

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

我希望能夠閱讀所有客戶信息。 有什么好的辦法嗎? 我已閱讀有關 Scanner 和 Pattern 的內容,想知道在這種情況下使用它們是否是個好主意? 我的文本文件非常大,包含數百個客戶。

有人知道我如何從文本文件中讀取所有信息嗎? 我創建了一個帶有客戶變量的 class,我只需要從文本文件中讀取的幫助。 我想以有組織的方式閱讀信息。

非常感謝所有幫助。

像這樣:

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並糾正你的硬件哈哈

作為對stas答案的一個小擴展:

最初發布的代碼不起作用,因為continue跳過了當前的循環迭代。 因此,除非該行以""開頭,否則什么都不會做。 但是不要對我投反對票,因為你的想法是正確的。

我更新了代碼(沒有測試它),它現在應該可以工作了。

如果您發布代碼來回答問題,您應該將其注釋掉,以便讀者能夠理解它的作用。

另外,不要乞求名譽,那是不禮貌的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM