如何读取制表符分隔的csv文件的特定列并解析特定列值的所有行值

时间:2014-11-07 11:40:49

标签: java

例如,如果我的输入csv文件包含

A    B     C     D      E
10   ab    a1    b1     ab1
20   cd    c1    d1     cd1    
30   ef    e1    f1     ef1
40   gh    c1    h1     gh1

我的输出..

Enter a value for C
c1
1)
A | 20
B | cd
C | c1
D | d1
E | cd1
2)
A | 40
B | gh
C | c1
D | h1
E | gh1

1 个答案:

答案 0 :(得分:1)

第一个读取行并按标签分割得到第二个索引的值。如果用户输入值,则打印所有值。例如

void cvsRead() throws FileNotFoundException, IOException {

        String line, userinput = "";
        BufferedReader br = new BufferedReader(new FileReader("yourfile.cvs"));
        Scanner scan = new Scanner(System.in);
        System.out.println("enter the column ");
        userinput = scan.nextLine();
        int i = 0;
        String[] spmap = br.readLine().split("\t");
        while ((line = br.readLine()) != null) {

            String[] sp = line.split("\t");
            if (sp[2].equals(userinput)) {
                i++;
                System.out.println(i + ")");
                for (int x = 0; x < spmap.length; x++) {
                    System.out.println(spmap[x] + " | " + sp[x]);
                }
            }

        }
    }

输出&GT;&GT;

enter the column 
c1
1)
A | 20
B | cd
C | c1
D | d1
E | cd1    
2)
A | 40
B | gh
C | c1
D | h1
E | gh1
相关问题