我有以下代码:
btnSaveTrip.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (showLog != null && showLog.getText().toString().length() > 0) {
File folder = new File(Environment.getExternalStorageDirectory() + "/tc");
if (!folder.exists()) {
folder.mkdir();
}
String externalStoragePath = Environment.getExternalStorageDirectory().toString();
final File file = new File(externalStoragePath + "/tc/strip.tcl");
try {
if (file.exists()) {
new AlertDialog.Builder(getActivity())
.setTitle("File Already Exist")
.setMessage("Do you want to overwrite the file?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
outputStream = new FileOutputStream(file);
outputStream.write(showLog.getText().toString().getBytes());
Toast.makeText (getActivity(), file.toString(), Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.show();
}
else {
outputStream = new FileOutputStream(file);
outputStream.write(showLog.getText().toString().getBytes());
Toast.makeText (getActivity(), file.toString(), Toast.LENGTH_SHORT).show();
}
}
catch (IOException e) {
e.printStackTrace();
Toast.makeText (getActivity(), "error in try", Toast.LENGTH_SHORT).show();
}
finally {
if(outputStream!=null) {
try {
outputStream.close();
Toast.makeText (getActivity(), "file closed", Toast.LENGTH_SHORT).show();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText (getActivity(), "error in finally catch", Toast.LENGTH_SHORT).show();
}
}
}
}
else {
Toast.makeText (getActivity(), "empty", Toast.LENGTH_SHORT).show();
}
}
});
我想做的是:
单击按钮时:
1)检查以使数据不为空或为空(工作正常):
if (showLog != null && showLog.getText().toString().length() > 0) {
2)检查以确保文件夹存在,如果不创建文件夹(工作正常):
File folder = new File(Environment.getExternalStorageDirectory() + "/tc");
if (!folder.exists()) {
folder.mkdir();
}
3)在将数据写入文件之前,确保它不存在。如果确实存在,则提示用户查看是否可以覆盖它。如果用户选择“是”,则覆盖文件,但如果用户选择“否”,则在文件名末尾添加“1”并保存。(不工作,需要帮助)
我收到以下行的错误:
outputStream = new FileOutputStream(file);
outputStream.write(showLog.getText().toString().getBytes());
错误:
未处理的异常类型 FileNotFoundException
--> (用 try/catch 包围)