Search code examples
javaandroidbufferedreaderreadfilefilenotfoundexception

Android - java.io.FileNotFoundException: /storage/emulated/0/Notes/File.txt: open failed: ENOENT (No such file or directory)


I found lot of topics with the same problem, but they couldn't fix mine. I initially write a file as follow:`

File root = new File(Environment.getExternalStorageDirectory(), "Notes");
    if (!root.exists()) {
        root.mkdirs();
    }
    File notefile = new File(root, sFileName);
    FileWriter writer = null;
    try {
        writer = new FileWriter(notefile);
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    try {
        writer.append(sBody);
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    try {
        writer.flush();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    try {
        writer.close();
    } catch (IOException e1) {
        e1.printStackTrace();
    }

Don't worry about the try and catch blocks, i will clear them later :D. And this is the reader which should works in the same directory ("Notes" of the sdcard, if it doesn't exist, will be created), read the file, and put it on a Notify as you can see:`

File root = new File(Environment.getExternalStorageDirectory(), "Notes");
    if (!root.exists()) {
        root.mkdirs();
    }

    File file = new File(root, "Nota.txt");


    //Read text from file
    text = new StringBuilder();

    try {
        BufferedReader br = new BufferedReader(new FileReader(file));
        String line;
        while ((line = br.readLine()) != null) {
            text.append(line);
            text.append('\n');
        }
        br.close() ;
    }catch (IOException e) {
        e.printStackTrace();
    }

I really don't understand why i get this problem, i even try with

getExternalStorageDirectory().getAbsolutePath() 

but without success.

Can someone help me?


Solution

  • Problem Solved

    I used SharedPreferences of Android. I stored the data in MainActivity and take in in my Class as follow:

    • MainActivity

      SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
      SharedPreferences.Editor editor = prefs.edit();
      editor.putString("string_id", InputString); //InputString: from the EditText
      editor.commit();
      
    • In my Class to get my data

      SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
      String data = prefs.getString("string_id", "no id"); //no id: default value