Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save file in Android: java.io.FileNotFoundException. open failed: ENOENT (No such file or directory)

Tags:

java

android

I've a next problem... I searched answer on the source, but didn't find a good answer...

java.io.FileNotFoundException: /mounted/EmailClient/side-corner.png: open failed: ENOENT (No such file or directory)
at libcore.io.IoBridge.open(IoBridge.java:453)
at java.io.FileOutputStream.<init>(FileOutputStream.
at java.io.FileOutputStream.<init>(FileOutputStream.java:73) etc

Code:

private static String saveFile(String filename, InputStream input) {
    String path = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(path)) {
        try {
            byte[] attachment = new byte[input.available()];
            input.read(attachment);
            File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/EmailClient/", filename);
            if (!file.mkdirs())
                Log.d("EmailClient", "saveFile: Dir not created");
            FileOutputStream out = new FileOutputStream(file); //PROBLEM!
            out.write(attachment);
            input.close();
            out.close();
            return path;
        } catch (IOException e) {
            Log.e("EmailClient", "saveFile: File not saved", e);;
        }
    }
    return path;
}
like image 618
Dzmitry Avatar asked Feb 07 '23 03:02

Dzmitry


1 Answers

use this code

File folder = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/EmailClient/");

folder.mkdirs();
File file = new File(folder,filename);
file.createNewFile();
like image 172
LearnPainLess Avatar answered Feb 08 '23 16:02

LearnPainLess