Please try this. I hope this code helps you.
CSVFileWriter.java
public class CSVFileWriter { private PrintWriter csvWriter; private File file; public CSVFileWriter(File file) { this.file = file; } public void writeHeader(String data) { try { if (data != null) { csvWriter = new PrintWriter(new FileWriter(file, true)); csvWriter.print(","); csvWriter.print(data); csvWriter.close(); } } catch (IOException e) { e.printStackTrace(); } } }
SampleActivity.java
public class SampleActivity extends Activity { CSVFileWriter csv; StringBuffer filePath; File file; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); saveButton = (Button) findViewById(R.id.button1); editText = (EditText) findViewById(R.id.editText1); filePath = new StringBuffer(); filePath.append("/sdcard/abc.csv"); file = new File(filePath.toString()); csv = new CSVFileWriter(file); saveButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { csv.writeHeader(editText.getText().toString()); } }); } }
Add this to the manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
source share