0

i have to read CSV file in java, I googled it but i got the way to read using the headers; but i have no information of the column headers and number of columns available in file. In this case How can i read CSV file.

Thanks

2
  • 10
    Read it into what? If you don't know what the fields mean or how many there are, what are you reading the CSV for? Commented Jun 23, 2011 at 12:09
  • 2
    or opencsv.sourceforge.net Commented Jun 23, 2011 at 12:09

3 Answers 3

3

You can assume every row to be of class String and read everything into an 2 dimensional array. Afterwards you could try to parse the strings into their appropriate Formats.

But if you do not know the row data type this is only a guess.

Sign up to request clarification or add additional context in comments.

Comments

2

If you don't know what the columns represent you can only read it as text with something like:

final BufferedReader br = new BufferedReader(new FileReader(file));
String line = null;
while ((line = br.readLine()) != null) {

    final String[] lineValues = line.split(COLUMN_DELIMITER);
}

This way all your column values will be in these lineValues arrays (column1 will be lineValues[0] etc.).

Comments

2

Casper datasets can do this is a few lines and will return a CDataRowSet which works in a similar way to a ResultSet. It can read the header from the file and return all Strings, eg:

CBuilder builder = new CBuildFromFile(new File("people.csv"));
CDataCacheContainer container = new CDataCacheContainer(builder);
CDataRowSet cdrs = container.getAll();

or it can also narrow the returned results to the smallest possible data type without losing fidelity. In doing so it can also handle missing integers and doubles (otherwise the resulting data type will remain as String), eg:

CBuilder builder = new CBuildNarrowedFile(new File("people.csv")).setConvertMissing(true);
CDataCacheContainer container = new CDataCacheContainer(builder);
CDataRowSet cdrs = container.getAll();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.