繁体   English   中英

在Android的SD卡中写入文件

[英]Write a file in SDcard in 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();

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

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

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();
}

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

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

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

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM