簡體   English   中英

如何從Java中具有逗號和半冒號的文件中讀取行

[英]How to read lines from a file that has commas and semi colons in Java

我知道我可以使用File Reader類。 但是,對於在一行中讀取文本的不同部分,我對實現感到困惑。

文件中的每一行都有名稱(名字和姓氏用空格隔開),但是用逗號分隔UKNOWN全名集。 然后使用分號將行內的部分分開。 下一部分由街道名稱組成(每個街道名稱也由逗號分隔)。

我要做的是將全名讀入字符串ArrayList中,當到達分號時,街道名稱應插入到單獨的字符串ArrayList中。

如果我能得到一個簡單的例子來說明如何繼續實施,那么我可以自己完成整個工作。

注意:它必須從文本文件中讀取。 每行將是一個全名和街道名稱的單獨測試用例。

編輯:

以下是輸入示例:James Cooper,John Evans,Abe Lincoln; Jackson st,No way,Aspen Way

輸出:包含名稱的數組列表= James Cooper,John Evans,Abe Lincoln(每個都用逗號分隔)

街道名稱的數組列表為= Jackson st,No way,Aspen Way(每個都用逗號分隔)

最簡單的操作可能是將整行讀入String ,然后多次使用Stringsplit()

String line; // Put the line in here however you're reading from the file.
String[] sections = line.split(";");
// Assuming you know there are always two sections, names and addresses:
String[] names = sections[0].split(",");
String[] addresses = sections[1].split(",");

// Convert arrays into ArrayLists if you actually need to
List<String> namesList = new ArrayList<>( Arrays.asList( names ) );
List<String> addressList = new ArrayList<>( Arrays.asList( addresses ) );

Scanner類足以滿足所有這些要求。 您必須根據要使用的分隔符(即分隔字符/字符串)來適當地使用方法useDelimiter()

如果您不介意引入額外的依賴關系,請查看OpenCSV( http://opencsv.sourceforge.net/ )。

這是一個非常基本的示例,它讀取一行(稱為“ nextLine”),然后將每個元素添加到dataArray中。 當它調用reader.readNext()時,它將更改為新行。 如果您確定只有兩行數據,則可以替換“ while”語句並先對名稱數組進行硬編碼,請先調用readNext(),然后再調用街道名稱數組。

    //Create the ArrayList to hold data
    ArrayList<String> dataArray =  new ArrayList<String>(); 

    //openCSV reader to parse the CSV file
    CSVReader reader = new CSVReader(new FileReader(f));

    //nextLine array contains a an entire row of data,
    //Each element represents a cell in the spreadsheet.
    String[] nextLine;

    //Iterate though the CSV while there are more lines to read
    while((nextLine = reader.readNext()) != null)
    {
                    //Iterate through the elements on this line
        for(String s : nextLine)
        {
            dataArray.add(s);
        }
    }

來源: http//opencsv.sourceforge.net/#how-to-read

-Kaz

暫無
暫無

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

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