簡體   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