Click here to Skip to main content
15,883,531 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I will select a csv file and then import the data to sqlite.i can also export the data from sqlite to csv file.if you simply show me to read/write CSV in android that will be good enough for me..Thanks in advanced
Posted

1 solution

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:
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:
Java
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:
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:
Java
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...
 
Share this answer
 
Comments
anel91 28-Aug-13 8:35am    
i have a question , i can't find the file output.csv in "C:\\work\\output.csv" ? where can i find it
csharpbd 28-Aug-13 11:16am    
1st you need to create "work" folder in "C:" root dir. then try this...
Member 11838412 16-Apr-16 5:21am    
in mobile there have no directory root like computer drive
SUKANTA MONDAL 20-Dec-17 15:12pm    
Can't find the output file even though i created the folder "work" in C dir

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900