Search code examples
javaandroidbitmapsd-card

Android writing bitmap to sdcard


I'm trying to write a bitmap to an sdcard on android, and I get the error message of
/mnt/sdcard/PhysicsSketchpad/sketchpad145.png (No such file or directory).
I declared the android.permission.WRITE_EXTERNAL_STORAGE permission in the manifest, and this is my code:

String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() + 
                        "/PhysicsSketchpad/";
File dir = new File(file_path);
dir.mkdirs();
File file = new File(dir, "sketchpad" + pad.t_id + ".png");
FileOutputStream fOut = new FileOutputStream(file);

bmp.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();

What's going on?

UPDATE

It seems as though when I try to write to an existing directory, I get an permission denied error,

08-11 09:55:23.796: WARN/Physics Sketchpad(8881): Error when saving: IOException /mnt/sdcard/download/sketchpad54.png (Permission denied)

and when I try to save in a new directory I get a no such file or directory error,
08-11 09:59:20.175: WARN/Physics Sketchpad(9040): Error when saving: IOException /mnt/sdcard/PhysicsSketchpad/sketchpad55.png (No such file or directory)

In addition, File.mkdirs() returns a boolean based on if it succeeded or not, and it returned false.


Solution

  • try this code.

      String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() + 
                                "/PhysicsSketchpad";
        File dir = new File(file_path);
    if(!dir.exists)
        dir.mkdirs();
        File file = new File(dir, "sketchpad" + pad.t_id + ".png");
        FileOutputStream fOut = new FileOutputStream(file);
    
        bmp.compress(Bitmap.CompressFormat.PNG, 85, fOut);
        fOut.flush();
        fOut.close();