Read CSV file column by column

前端 未结 8 1689
萌比男神i
萌比男神i 2020-11-29 04:31

I want to read specific columns from a multi column csv file and print those columns in other csv file using Java. Any help please? Following is my code to print each token

8条回答
  •  时光取名叫无心
    2020-11-29 05:15

    I sugges to use the Apache Commons CSV https://commons.apache.org/proper/commons-csv/

    Here is one example:

        Path currentRelativePath = Paths.get("");
        String currentPath = currentRelativePath.toAbsolutePath().toString();
        String csvFile = currentPath + "/pathInYourProject/test.csv";
    
        Reader in;
        Iterable records = null;
        try
        {
            in = new FileReader(csvFile);
            records = CSVFormat.EXCEL.withHeader().parse(in); // header will be ignored
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    
        for (CSVRecord record : records) {
            String line = "";
            for ( int i=0; i < record.size(); i++)
            {
                if ( line == "" )
                    line = line.concat(record.get(i));
                else
                    line = line.concat("," + record.get(i));
            }
            System.out.println("read line: " + line);
        }
    

    It automaticly recognize , and " but not ; (maybe it can be configured...).

    My example file is:

    col1,col2,col3
    val1,"val2",val3
    "val4",val5
    val6;val7;"val8"
    

    And output is:

    read line: val1,val2,val3
    read line: val4,val5
    read line: val6;val7;"val8"
    

    Last line is considered like one value.

提交回复
热议问题