我一直在搜索这个问题。 它实际上在较旧版本的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();
P.S。好吧,我已经改变了,就像你们提到的那样,我的代码,但它仍然给我同样的错误,它不是目录......任何想法???
答案 0 :(得分: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();
}
答案 1 :(得分:1)
您只需要更改为以下代码,因为您缺少“/”:
myFile = new File(path,"/mysdfile.xml");
但请记住,您必须拥有在清单文件中写入外部存储空间的权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>