请试试这个。我希望这段代码对你有帮助。
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());
}
});
}
}
将此添加到清单文件中
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />