简体   繁体   中英

Reading Text file in android

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM