javaJunk
javaJunk

Reputation: 21

Using I/O stream to parse CSV file

I have a CSV file of US population data for every county in the US. I need to get each population from the 8th column of the file. I'm using a fileReader() and bufferedStream() and not sure how to use the split method to accomplish this. I know this isn't much information but I know that I'll be using my args[0] as the destination in my class.

I'm at a loss to where to being to be honest.

import java.io.FileReader;

public class Main {

    public static void main(String[] args) {
      BufferedReader() buff = new BufferedReader(new FileReader(args[0]));
      String 
    }
    try {

    }
}

The output should be an integer of the total US population. Any help with pointing me in the right direction would be great.

Upvotes: 1

Views: 743

Answers (1)

madhead
madhead

Reputation: 33491

Don't reinvent the wheel, don't parse CSV yourself: use a library. Even such a simple format as CSV has nuances: fields can be escaped with quotes or unescaped, the file can have or have not a header and so on. Besides that you have to test and maintain the code you've wrote. So writing less code and reusing libraries is good.

There are a plenty of libraries for CSV in Java:

IMHO, the first two are the most popular.

Here is an example for Apache Commons CSV:

final Reader in = new FileReader("counties.csv");
final Iterable<CSVRecord> records = CSVFormat.DEFAULT.parse(in);

for (final CSVRecord record : records) { // Simply iterate over the records via foreach loop. All the parsing is handler for you
    String populationString = record.get(7); // Indexes are zero-based
    String populationString = record.get("population"); // Or, if your file has headers, you can just use them

    … // Do whatever you want with the population
}

Look how easy it is! And it will be similar with other parsers.

Upvotes: 3

Related Questions