java - 在Android中向SD卡写入文件

标签 java android

我一直在寻找这个问题。 它实际上可以在旧版本的 android 中运行,但是在我更新 SDK 后,出现错误。 错误消息为“打开的文件:ENOTDIR(不是目录):/sdcard/PlayNumbers/mysdfile.xml” 有人可以指出我做错了什么吗? 我的代码如下。

非常感谢,

path=new File("/sdcard/PlayNumbers");
myFile = new File(path,"mysdfile.xml");
if (!path.exists()) {
    path.mkdirs();
}
if(!myFile.exists()){
    myFile.createNewFile();
}

FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);

myOutWriter.append("test");
myOutWriter.close();
fOut.close();

==>

File path = null;
File myFile = null;
String filePath = Environment.getExternalStorageDirectory().toString();
path=new File(filePath+"/PlayNumbers/");
myFile = new File(path,"mysdfile.xml");

//i also tried both as below
//path=new File(filePath+"/PlayNumbers");
//myFile = new File(path,"mysdfile.xml");

if (!path.exists()) {
    path.mkdirs();
}
if(!myFile.exists()){
    myFile.createNewFile();
}
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append("test");
myOutWriter.close();
fOut.close();

附:好吧,我已经改变了,正如你们提到的,就像我的代码一样,但它仍然给我同样的错误,它不是目录......有什么想法吗???

最佳答案

假设您在 list 中拥有正确的权限,这应该可行:

File externalStorageDir = Environment.getExternalStorageDirectory();
File playNumbersDir = new File(externalStorageDir, "PlayNumbers");
File myFile = new File(playNumbersDir, "mysdfile.xml");

if (!playNumbersDir.exists()) {
    playNumbersDir.mkdirs();
}
if(!myFile.exists()){
    myFile.createNewFile();
}

关于java - 在Android中向SD卡写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14514363/

相关文章:

java - 什么时候可以很快使用新的 Java 特性?

java - Postgres 中的 NamedParameterJdbcTemplate 和 JSON

java - Istio 返回 "RBAC: access denied"并带有通配符路径

java - 在 hql 中使用 select * 但获取值的地址

android - 找人在 android 项目上工作

android - 如何在 Kotlin 中关闭 Android 应用程序

android - 无法在运行时更改开关文本开/关

java - 实现 OnClickListener VS。新的 Button.OnClickListener() {};

android - 将具有空值的字符串作为参数传递时, Volley 字符串请求错误

c# - 如何在 visual studio 中使用 C# android 创建 android 小部件