gpt4 book ai didi

java - 在 Android 中将文件写入 SDcard

转载 作者:搜寻专家 更新时间:2023-11-01 08:05:44 25 4
gpt4 key购买 nike

我一直在寻找这个问题。它实际上适用于旧版本的 android,但在我更新 SDK 后,出现错误。错误信息是“open filed: ENOTDIR (Not a directory):/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 中将文件写入 SDcard,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14514363/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com