无法保存带有时间戳的新文件
Posted
技术标签:
【中文标题】无法保存带有时间戳的新文件【英文标题】:failed to save new file with time stamp 【发布时间】: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” 那么如果文件夹不存在如何自动创建呢?
或者我的编码有什么问题吗? 每次按下保存按钮我都想保存新文件而不是覆盖以前的文件
【问题讨论】:
【参考方案1】:先创建目录(如果已经存在则不会报错):
File directory = new File(Environment.getExternalStorageDirectory(), "Preposisi Removal/");
directory.mkdirs();
然后在该目录中创建文件(使用带有时间戳和后缀的完整名称):
File myFile = new File(directory, "PreposisiRemoval" + filename); //Changed code
//myFile.getParentFile().mkdir(); //No longer required
myFile.createNewFile();
FileOutputStream FOut = new FileOutputStream(myFile); //Changed code
编辑:
好的,现在我看到了实际问题:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd'/'HHmm");
文件名的时间戳部分包含一个“/”。您不能在文件名中使用该字符,因为它表示文件夹或目录。换成其他字符,例如:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd'_'HHmm");
您的代码(或我之前建议的更新)应该可以工作。
【讨论】:
错误先生,得到消息“打开失败:ENOENT(没有这样的文件或目录) SD 卡是否可用,您是否在清单中有 WRITE_EXTERNAL_STORAGE 权限?我看到你在前面的代码中检查了外部存储状态,然后不管结果如何都去保存文件。 我在 android manifest 中有这样的权限以上是关于无法保存带有时间戳的新文件的主要内容,如果未能解决你的问题,请参考以下文章
macOS:SwiftUI:MenuItem 用于截取 WKWebView 的屏幕截图并将其保存到带有时间戳的 ~/Pictures?
使用 FeatureTools 到带有时间戳的 normalize_entity 时无法转换列