Java doesn’t support parsing of CSV files natively, we have to rely on third party library. There was 3rd party library
Opencsv is very good library to read and write CSV file in android platform.
At first you need to download this library
Download. Then try...
Reading CSV file in Java:
String csvFilename = "C:\\sample.csv";
CSVReader csvReader = new CSVReader(new FileReader(csvFilename));
String[] row = null;
while((row = csvReader.readNext()) != null) {
System.out.println(row[0]
+ " # " + row[1]
+ " # " + row[2]);
}
csvReader.close();
Above code read csv file line by line. If you want to read full document once using below code:
String[] row = null;
String csvFilename = "C:\\work\\sample.csv";
CSVReader csvReader = new CSVReader(new FileReader(csvFilename));
List content = csvReader.readAll();
for (Object object : content) {
row = (String[]) object;
System.out.println(row[0]
+ " # " + row[1]
+ " # " + row[2]);
}
csvReader.close();
Writing CSV file in Java:
String csv = "C:\\work\\output.csv";
CSVWriter writer = new CSVWriter(new FileWriter(csv));
String [] country = "India#China#United States".split("#");
writer.writeNext(country);
writer.close();
Above code use to write a string array in csv, but you can write a full document or list of string array using below code:
String csv = "C:\\work\\output.csv";
CSVWriter writer = new CSVWriter(new FileWriter(csv));
List<string[]> data = new ArrayList<string[]>();
data.add(new String[] {"India", "New Delhi"});
data.add(new String[] {"United States", "Washington D.C"});
data.add(new String[] {"Germany", "Berlin"});
writer.writeAll(data);
writer.close();
Try this i think it work fine for you...