0

I am trying to read a text file stored in my mobile device external storage , but it is throwing this error: - Error occured while reading text file!!/storage/emulated/0/atom.txt: open failed: ENOENT (No such file or directory) Here's the code

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button button = (Button) findViewById(R.id.btn_picker);

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            try {
                fileOpener();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });

}

private void fileOpener() throws IOException {
    File sdcard = Environment.getExternalStorageDirectory();

    //Get the text file
    File file = new File(sdcard,"atom.txt");
    //Read text from file
    StringBuilder text = new StringBuilder();

    try {
        BufferedReader br = new BufferedReader(new FileReader(file));
        String line;

        while ((line = br.readLine()) != null) {
            text.append(line);
            text.append('\n');
        }
    }
    catch (IOException e) {

        Log.e("Error", "Error occured while reading text file!!" + e.getMessage());
    }

    //Find the view by its id
  Log.d("Text",text.toString());
} 

}

How can I figure this out?
EDIT : The atom.txt file is already saved in my device but still it is throwing the same error.

Logan
  • 101
  • 1
  • 2
  • 12

1 Answers1

0

The file doesn't exist, so the path returned by Environment.getExternalStorageDirectory is not what you are expecting it to be. According to the API docs, this path is not guaranteed to be an SD card.

acallan
  • 34
  • 2
  • Ok i get it what you just said , but can you please tell me what changes should i do in above code in order to run it properly . It would be helpful for me. – Logan Oct 11 '17 at 20:32