Java.io.FileNotFoundException: /storage/emulated/0/saved_images/grub.jpg: open failed: ENOENT (There is no such file or directory)

Using the code below to save the image on the SD card, but I keep getting this exception below

private void SaveImage(Bitmap finalBitmap,String filename) { String root = Environment.getExternalStorageDirectory().toString(); File myDir = new File(root + "/saved_images"); myDir.mkdirs(); String fname = filename; File file = new File (myDir, fname); if (file.exists ()) file.delete (); try { FileOutputStream out = new FileOutputStream(file); finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out); out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); } } 

Am I missing something here?

+6
source share
4 answers

Change the code as you are not creating a directory.

 private void SaveImage(Bitmap finalBitmap,String filename) { String root = Environment.getExternalStorageDirectory().toString(); File myDir = new File(root + "/saved_images"); myDir.mkdirs(); String fname = filename; File file = new File (myDir, fname); if (file.exists ()) file.delete (); file.createNewFile(); try { FileOutputStream out = new FileOutputStream(file); finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out); out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); } 

}

+7
source

This is how I read the file from the repository when I checked the timestamp in a text file. Line 2 is probably the best choice for you.

 File root = android.os.Environment.getExternalStorageDirectory(); File dir = new File(root.getAbsolutePath() + "/path"); dir.mkdirs(); File file = new File(dir, ".storage.txt"); Reader pr; String line = ""; try { pr = new FileReader(file); int data = pr.read(); while (data != -1) { line += (char) data; data = pr.read(); } pr.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } //do stuff with line 
+1
source

From Android 6.0.0 you need to use this code:

 if (ContextCompat.checkSelfPermission(thisActivity, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) 
+1
source

make sure you post permissions for the manifest:

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

Source: https://habr.com/ru/post/979309/


All Articles