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
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).
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.
In order to get each value one at a time, use a StringTokenizer. Construct it with (Not recommended)StringTokenizer(str, ",")
.
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)
.