簡體   English   中英

如何從 Android 10 中的外部存儲“文檔”中讀取文件?

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

Android 開發新手,我需要幫助。

此代碼/功能在 Android Studio 的內置仿真器中使用 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;
}

代碼只是讀取公用文件夾“Documents”中的文件並將內容作為字符串數組返回。 但由於某種原因,此代碼在 Android 10 中不起作用。

清單文件包括這兩個請求:

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

您可以使用相同的代碼。

但是對於 Android 10 設備,您應該添加

 requestLegacyStorageLocation="true"

(或類似的東西)在清單文件的應用程序標簽中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM