2

我一直在寻找这个问题。它实际上在旧版本的 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();

ps好的,我已经改变了你们提到的我的代码,但它仍然给我同样的错误,它不是目录......任何想法?

4

2 回答 2

3

假设您在清单中具有正确的权限,这应该可以工作:

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();
}
于 2013-01-25T03:45:30.853 回答
1

您只需要更改为以下代码,因为您缺少“/”:

myFile = new File(path,"/mysdfile.xml");

但请记住,您必须具有在清单文件中写入外部存储的权限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
于 2013-01-25T02:34:55.423 回答