2

i have a very small problem. I am writing a file to sdcard. I'l show you two code, one code works and other doesn't. It looks like this: First one,

new FileOutputStream("/sdcard/HelloWorld.txt")

This works fine and creates a HelloWorld.txt file in sdcard.

Now second one,

  new FileOutputStream(android.os.Environment.getExternalStorageDirectory()+java.io.File.separator + "filetest" + java.io.File.separator + "HelloWorld.txt")

This throws error "/mnt/sdcard/filetest/HelloWorld.txt (No such file or directory)". I want to know why because i have mnt/sdcard path on my device, is it that it cannot find filetest folder if yes then isn't it supposed to create filetest folder if its not created before.

Thanks.

user370305
  • 108,599
  • 23
  • 164
  • 151
padam thapa
  • 1,471
  • 2
  • 20
  • 41

2 Answers2

4

First Make a directory of filetest if its not available,

File file = new File(android.os.Environment.getExternalStorageDirectory()+java.io.File.separator + "filetest");

file.mkdir();

Then execute your code...

OR

File f =    new File(android.os.Environment.getExternalStorageDirectory()+java.io.File.separator + "filetest" + java.io.File.separator + "HelloWorld.txt");

    if (!f.getParentFile().exists());
    {
        f.getParentFile().mkdir();
    }
user370305
  • 108,599
  • 23
  • 164
  • 151
2

Yes........ filetest folder are not there so you need to create it manually or programatically.and try that code...so you get success.

you can also create dir like this ::

File wallpaperDirectory = new File("/sdcard/filetest/");
// have the object build the directory structure, if needed.
wallpaperDirectory.mkdirs();
// create a File object for the output file
File outputFile = new File(wallpaperDirectory, filename);
// now attach the OutputStream to the file object, instead of a String representation
FileOutputStream fos = new FileOutputStream(outputFile);

Use Permission :::

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Nikunj Patel
  • 21,853
  • 23
  • 89
  • 133