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:
---------------------------------------------
FirstParam |
SecondParam |
ThirdParam |
0.31 |
5.2 |
7 |
0.31 |
5.2 |
7.1 |
0.31 |
5.2 |
7.2 |
|
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();
|
FirstParam |
SecondParam |
ThirdParam |
0.31 |
5.2 |
7 |
|
0.31 |
5.2 |
7.1 |
|
0.31 |
5.2 |
7.2 |
|
Comments (0)
You don't have permission to comment on this page.