wjae
wjae

Reputation: 166

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

p.s. 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???

Upvotes: 2

Views: 2842

Answers (2)

GreyBeardedGeek
GreyBeardedGeek

Reputation: 30088

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

Upvotes: 3

Husam A. Al-ahmadi
Husam A. Al-ahmadi

Reputation: 2056

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"/>

Upvotes: 1

Related Questions