Parsing CSV in java

后端 未结 9 1814
臣服心动
臣服心动 2020-11-27 21:12

I have this weird situation where I have to read horizontally. So I am getting a csv file which has data in horizontal format. Like below:

CompanyName,RunDat         


        
相关标签:
9条回答
  • 2020-11-27 22:02

    You should really try univocity-parsers as its CSV parser comes with many features to handle all sorts of corner cases (unescaped quotes, mixed line delimiters, BOM encoded files, etc), which is also one of the fastest CSV libraries around.

    Simple example to parse a file:

    CsvParserSettings settings = new CsvParserSettings(); //heaps of options here, check the docs
    CsvParser parser = new CsvParser(settings);
    
    //loads everything into memory, simple but can be slow.
    List<String[]> allRows = parser.parseAll(new File("/path/to/your.csv"));
    
    //parse iterating over each row
    for(String[] row : parser.iterate(new File("/path/to/your.csv"))){
        //process row here
    }
    
    //and many other possibilities: Java bean processing, column selection, format detection, etc.
    

    Disclosure: I am the author of this library. It's open-source and free (Apache V2.0 license).

    0 讨论(0)
  • 2020-11-27 22:03

    By far the most useful page on the subject of CSV parsing I've ever found is the following:

    http://secretgeek.net/csv_trouble.asp

    Basically, get an established library to do it for you, because csv parsing is deceptively tricky.

    0 讨论(0)
  • 2020-11-27 22:07

    In order to get each value one at a time, use a StringTokenizer. Construct it with StringTokenizer(str, ","). (Not recommended)

    Use the split() method of the string class, which loads all of the tokens into an array.

    Use the DateFormat class to parse each date -- specifically DateFormat.parse(String).

    0 讨论(0)
提交回复
热议问题