【发布时间】:2017-11-16 19:03:57
【问题描述】:
我正在尝试创建 txt 文件并将其写入 android 的 sdcard 上。我收到“未创建目录”错误。 path.mkdirs() 应该创建所需的目录,不是吗?我在AndroidManifest.xml 中有<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />,并且我已经开启了应用的存储权限。
安卓版本:7.0
public void addData(View v) {
wordList.add(inAddWord.getText().toString());
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
File file = new File(path, "wordDatabase.txt");
try {
if(!(path.exists() && path.isDirectory())) {
while (!path.mkdir()) {
Log.e("Path", "Directory not created");
}
}
OutputStream os = new FileOutputStream(file);
os.write((inAddWord.getText().toString() + "\n").getBytes());
os.close();
} catch (IOException e) {
e.printStackTrace();
Log.w("ExternalStorage", "Error writing " + file, e);
}
}
【问题讨论】:
-
您还应该在该 catch 块中放置一个 toast,以便在该 catch 发生时通知用户。
-
while (!path.mkdir()) { Log.e("Path", "Directory not created");。错误代码。如果无法创建目录,您的应用程序将挂起。一次又一次地尝试是没有意义的。将 while 更改为 if。如果 mkdir 失败,并添加一个 toast 以通知用户。并返回。继续下去是没有意义的。请在此处调整您的代码并进行更新。 -
if(!(path.exists() && path.isDirectory())。不,应该是if(!path.exists())。 -
现在可以使用了,谢谢。文件是在我没有查看的内部存储上创建的,因为我认为
Environment.getExternalStoragePublicDirectory()仅将目录返回到 SD 卡。