简体   繁体   中英

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

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" />

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.

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