简体   繁体   中英

Write a file in SDcard in Android

I have been searching this problem. It actually worked in older version of android, but after I updated SDK, I get an error. Error message is "open filed: ENOTDIR (Not a directory): /sdcard/PlayNumbers/mysdfile.xml" Can please someone point me what I did wrong?? My codes are below.

Many Thanks,

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 ok, I have changed as you guys mentioned like my code, but it still gives me same error that it is not directory... any idea???

This should work, assuming that you have the correct permission in your manifest:

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

you just need to change to the following code because you missing "/":

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

But keep in mind that you have to have the permission for writing in external storage in your manifest file :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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