简体   繁体   中英

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

How do I read 2 particular column(1st column and 3rd Column) from a txt file. The main problem is that the columns are separated by different delimiters(I want to ignore the 2nd column in which (base 16) is written). Also how do I skip the column headings. The txt file looks as follows:

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

I was trying with the following piece of code. But its not working.

    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);
        }
    }

So Basically I want to read D0-AB-DB and Ahenhen ViewAt Technology Co.,Ltd. in 1st line and after that I want to read 42-05-F5 and Integrated Technology (Malaysia) Sdn. Bhd. Integrated Technology (Malaysia) Sdn. Bhd. in 2nd line.

What regular expression should I use in this case. A sample code would be helpful.

Thanx in Advance!!

Re-write your while loop as follows:

    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);
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM