我正在尝试编写将edittext内容保存到SD卡中的文件的代码。我发现以下代码有效:
public void onClick(View v) {
// write on SD card file data in the text box
try {
File myFile = new File("/sdcard/mysdfile.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(write_text.getText());
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Done writing SD 'mysdfile.txt'",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}// onClick
}); // btnWriteSDFile
问题是,这总是将信息保存到同一个文件中,覆盖以前的任何保存。
如果给定文件存在,如何提示用户输入文件的其他名称并将其保存在用户提供的名称下?
注意,我对此很陌生。
答案 0 :(得分:0)
我可以建议一种方式..
在onclick()中弹出一个带有in this link等编辑文本的自定义警告对话框,并要求用户输入名称,并在File myFile = new File("/sdcard/"+myfilename+".txt");
答案 1 :(得分:0)
首先
从提示对话框中获取文件名
public void onClick(View v) {
// write on SD card file data in the text box
try {
AlertDialog.Builder alert = new AlertDialog.Builder(this.getApplicationContext());
alert.setTitle("Title");
alert.setMessage("Message");
// Set an EditText view to get user input
final EditText input = new EditText(this.getApplicationContext());
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Editable value = input.getText();
File myFile = new File("/sdcard/"+value .toString());
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(write_text.getText());
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Done writing SD 'mysdfile.txt'",
Toast.LENGTH_SHORT).show();
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();
}