如何从Java中的txt文件中读取2个特定列?

时间:2018-01-19 06:04:32

标签: java regex hashmap delimiter file-handling

如何从txt文件中读取2个特定列(第1列和第3列)。主要问题是列由不同的分隔符分隔(我想忽略写入(基数16)的第2列)。另外我如何跳过列标题。 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);
        }
    }

所以基本上我想在第1行阅读D0-AB-DBAhenhen ViewAt Technology Co.,Ltd.,之后我想在第2行阅读42-05-F5Integrated Technology (Malaysia) Sdn. Bhd.

在这种情况下我应该使用什么正则表达式。示例代码会有所帮助。

Thanx提前!!

1 个答案:

答案 0 :(得分:1)

重写你的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);
        }
    }