add this permission in manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
This example shows how to create a CSV file on removable storage in Android. CSV files are a convenient storage format for data to be easily viewed in programs like Excel or OpenOffice.
In this example, my goal is to create a CSV file having the following text:
---------------------------------------------
|
Add this code to open a new file called "mydata.csv" on the SD card:
import java.io.File;
import java.io.FileWriter; import java.io.IOException; import android.os.Environment;
---------------------------------------------
FileWriter writer;
File root = Environment.getExternalStorageDirectory();
File gpxfile = new File(root, "mydata.csv"); |
Use this routine to write the csv headers:
private void writeCsvHeader(String h1, String h2, String h3) throws IOException { String line = String.format("%s,%s,%s\n", h1,h2,h3); writer.write(line); } |
Use this routine to write CSV values to the file:
private void writeCsvData(float d, float e, float f) throws IOException { String line = String.format("%f,%f,%f\n", d, e, f); writer.write(line); } |
Write the header and data lines like this:
try {
writer = new FileWriter(gpxfile);
writeCsvHeader("FirstParam","SecondParam","ThirdParam");
writeCsvData(0.31f,5.2f,7.0f); writeCsvData(0.31f,5.2f,7.1f); writeCsvData(0.31f,5.2f,7.2f);
} catch (IOException e) {
e.printStackTrace(); } |
Quick note: adding "f" to the end of the constant number above tells Java you explicitly want to pass the value as a float, instead of a double.
Don't forget to close the file:
writer.flush(); writer.close(); |