Home > database >  How to read files from external storage "Documents" in Android 10?
How to read files from external storage "Documents" in Android 10?

Time:08-06

New to Android development here, and I need help.

This code/function is working in the built-in emulator of Android Studio with Android 11.

private String[] getData(String filename) throws IOException {

    FileInputStream fin = null;
    int ch;
    StringBuffer sb = new StringBuffer();
    String text = "";
    String[] fragments = new String[0];
    try{
        fin = new FileInputStream(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS) "/" filename);
        while((ch = fin.read()) != -1) {
            sb.append((char)ch);
        }
        text = sb.toString();
        fragments = text.split(";");
    }
    catch (FileNotFoundException e) {
        System.out.println("File not found"   e);
    }
    catch (IOException ioe) {
        System.out.println("Exception while reading file "   ioe);
    }
    finally {
        // close the stream using close method
        try {
            if (fin != null) {
                fin.close();
            }
        }
        catch (IOException ioe) {
            System.out.println("Error while closing stream: "   ioe);
        }
    }
    return fragments;
}

The code just read the file in the public folder "Documents" and return the contents as array of Strings. But for some reason, this code doesn't work in Android 10.

The manifest file includes these two requests:

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

CodePudding user response:

You can use the same code.

But for an Android 10 device you should add

 requestLegacyStorageLocation="true"

(or something like that ) in application tag of manifest file.

  • Related