保存文件我有以下代碼:Android中
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)澈CK,以確保該文件夾存在,如果無法創建文件夾(做工精細):
File folder = new File(Environment.getExternalStorageDirectory() + "/tc");
if (!folder.exists()) {
folder.mkdir();
}
3)之前將數據寫入到文件,確保它不存在。如果確實存在,請提示用戶查看是否可以覆蓋。如果用戶選擇YES,則覆蓋該文件,但如果用戶選擇NO,則在文件名末尾添加「1」並保存。 (沒有工作,需要幫助)
我得到一個錯誤的下面一行:
outputStream = new FileOutputStream(file);
outputStream.write(showLog.getText().toString().getBytes());
錯誤:
Unhandled exception type FileNotFoundException
--> (Surround with try/catch)
很好用。謝謝。 – Si8