【发布时间】:2014-01-16 23:50:13
【问题描述】:
我想将文件保存到 sd 卡中,我使用时间戳,所以如果已经有一个同名的文件不会被替换 这是我的代码
public void onClick(View v) {
// TODO Auto-generated method stub
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
} else {
mExternalStorageAvailable = mExternalStorageWriteable = false;
}
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd'/'HHmm");
String timestamp = dateFormat.format(new Date());
String filename = "_" + timestamp + ".txt";
File myFile = new File(Environment.getExternalStorageDirectory(), "Preposisi Removal/PreposisiRemoval");
myFile.getParentFile().mkdir();
myFile.createNewFile();
FileOutputStream FOut = new FileOutputStream(myFile+filename);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(FOut);
myOutWriter.append(tv.getText());
myOutWriter.close();
FOut.close();
Toast.makeText(getBaseContext(), "Save Files Successful", Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
button = (Button) findViewById(R.id.button7);
button.setOnClickListener (this);
}
但是当我运行它时,我收到了 toast 消息“/mnd/sdcard/Preposisi Removal/PreposisiRemoval_20140117/0633.txt: open failed:ENOENT (No such file or directory)
我猜是因为没有文件夹“Preposisi Removal” 那么如果文件夹不存在如何自动创建呢?
或者我的编码有什么问题吗? 每次按下保存按钮我都想保存新文件而不是覆盖以前的文件
【问题讨论】:
标签: java android eclipse save timestamp