簡體   English   中英

如何從 Java 中的 txt 文件中讀取 2 個特定列?

[英]How do I read 2 particular columns from a txt file in Java?

如何從 txt 文件中讀取 2 個特定列(第一列和第三列)。 主要問題是列由不同的分隔符分隔(我想忽略寫入(基數為 16)的第二列)。 另外我如何跳過列標題。 txt 文件如下所示:

IOU/AB-L                                                    Organization                                 
company_id                                                  Organization                                 
                                                            Address                                      

D0-AB-DB   (hex)             Ahenhen ViewAt Technology Co.,Ltd. 
D0ABDB     (base 16)         Ahenhen ViewAt Technology Co.,Ltd. 
                             9A,Microprofit,6th Gaoxin South Road, High-Tech 
                             Industrial Park, Nanshan, henzhen.
                             henzhen  guangdong  51867
                             DN

42-05-F5   (hex)            Integrated Technology (Malaysia) Sdn. Bhd.
4205F5     (base 16)        Integrated Technology (Malaysia) Sdn. Bhd.
                            Phase 1, Bayan Aepas FIZ
                            Bayan Lepas  Penang  11923
                            NY

我正在嘗試使用以下代碼。 但它不起作用。

    String line;
    BufferedReader reader = new BufferedReader(new FileReader(path));
    while ((line = reader.readLine()) != null) {
        String[] parts = line.split("   ", 3);
        if (parts.length >= 3) {
            String key = parts[0];
            String value = parts[2];
            System.out.println("Key value pair is " + key + "   " + value);
            map.put(key, value);
        } else {
            System.out.println("ignoring line: " + line);
        }
    }

所以基本上我想讀D0-AB-DBAhenhen ViewAt Technology Co.,Ltd. 在第一行,之后我想閱讀42-05-F5Integrated Technology (Malaysia) Sdn. Bhd. Integrated Technology (Malaysia) Sdn. Bhd.在第二行。

在這種情況下我應該使用什么正則表達式。 示例代碼會有所幫助。

提前致謝!!

重新編寫您的 while 循環,如下所示:

    while ((line = reader.readLine()) != null) {
        String[] parts = line.split("\\((hex)\\)", 3);

        if (parts.length >= 2) {
            String key = parts[0].trim();
            String value = parts[1].trim();
            System.out.println("Key value pair is :" + key + "   " + value);
            map.put(key, value);
        } else {
            System.out.println("ignoring line: " + line);
        }
    }

暫無
暫無

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

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