Harshit Kumar
Harshit Kumar

Reputation: 512

FIleNotFoundException when I am trying to save a file

I have put the following permissions to my manifest file

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

The following is the function on which the compiler is showing error:

private void save(String s) {
    FileOutputStream stream = null;

    File notes = new File(Environment.getExternalStorageDirectory().toString() + "/SystemService", "samples.txt");
    Log.i(LOGTAG, Environment.getExternalStorageDirectory().toString() + "/SystemService");

    try {
        stream = new FileOutputStream(notes);
        stream.write(s.getBytes());
    } catch (IOException e) {
        e.printStackTrace();
    } finally {

        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

}

SystemService is the folder name where I want to store my newly created folder in which I want the text files to be stored on my external storage device. (I have a marshmallow running device and I have given storage permission to the app)

The exact error is

java.io.FileNotFoundException: /storage/emulated/0/SystemService/samples.txt: open failed: ENOENT (No such file or directory)

Upvotes: 0

Views: 1326

Answers (1)

petey
petey

Reputation: 17140

To fix the FileNotFoundException, create the missing folders, if needed by calling File#mkdirs. Here is an example with some minor clean up (logging of exceptions, deleting older file if it exists). HTHs!

private void save(String s) {
    FileOutputStream stream = null;
    File notes = new File(Environment.getExternalStorageDirectory(), "SystemService/samples.txt");
    if (!notes.exists()) {
        // creates the missing folders for this file
        notes.mkdirs();
    }
    Log.i(LOGTAG, notes.getAbsolutePath().toString());

    try {
        stream = new FileOutputStream(notes);
        stream.write(s.getBytes());
    } catch (IOException e) {
        // use log.e for errors
        Log.e(LOGTAG, e.getMessage(), e);
    } finally {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                Log.e(LOGTAG, e.getMessage(), e);
            }
        }

    }
}

From the File#mkdirs documentation

Creates the directory named by this file, creating missing parent directories if necessary. Use mkdir() if you don't want to create missing parents.

Upvotes: 1

Related Questions