-3

I'm currently trying to write a program that can load a selected text file from internal/external storage for use in an Android application.

I've already tried loading the file using the following code via this page to no avail:

File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard,"file.txt");

and this (thanks to Google)

public void performFileSearch() {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.setType("text/plain");
startActivityForResult(intent, READ_REQUEST_CODE);
}

@Override
public void onActivityResult(int requestCode, int resultCode,
                             Intent resultData) {
    super.onActivityResult(requestCode, resultCode, resultData);
    if (requestCode == READ_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
        Uri uri = null;
        if (resultData != null) {
            uri = resultData.getData();
            Log.i(TAG, "Uri: " + uri.getPath());
            File file = new File(uri.getPath());
            if (file.exists()) {
                Log.i(TAG, "Exists");
            } else {
                Log.i(TAG, "Does not exist");
            }
        }
    }
}

In the later case, (where the user selects a text file) when a text file is selected it surprisingly returns false. I also get similar errors for the first block of code. I read that you can load a file from a uri using an InputStream, but I don't know how to implement this. Thanks for any and all the help.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Alex S
  • 125
  • 6

1 Answers1

0

File file = new File(sdcard,"file.txt");

don't mean file is there. You check it, the data read it like.

    File sdcard = Environment.getDataDirectory();
    File file = new File(sdcard,"file.txt");
    if (file.exists()) {
        InputStream readData;
        byte[] buffer = new byte[4096];
        int readLength;
        try {
            readData = new FileInputStream(file);
            while ((readLength = readData.read(buffer)) > 0) {
                // do work here to data
                // readLength 4096 not always, last not as much often
            }
            readData.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {
        // do nothing file exist
    }

must have set the permisssions to create if not exception will happen.

many ways of data reading

  • Hi, thanks for the response. I've tried your code, and it says that the file exists, but it's still showing that the file cannot be read. Any suggestions? – Alex S Sep 16 '19 at 21:19