簡體   English   中英

使用Release APK中的Intent.ACTION_OPEN_DOCUMENT讀取大文本文件時,IOException EBADF(錯誤文件描述符)

[英]IOException EBADF (Bad file descriptor) when reading large text files using Intent.ACTION_OPEN_DOCUMENT in Release APK

在我的Android應用程序中,我提供了一個菜單,用於通過Intent.ACTION_OPEN_DOCUMENT導入文本文件(它包含一些稍后將使用gson處理的Json數據)。 這些文件可能很大,5 MB或更大。

問題:當我直接從手機上的Android Studio啟動應用程序時,一切都正常,也適用於大文件。 但是對於發行版apk,如果文件大於500kb(異常由readLine引發),我將獲得IOException EBADF(錯誤文件描述符)。 如果我從Google驅動器或下載文件中讀取文件,情況就是如此。

我使用以下方法(從我的Activity中調用)讀取了代碼:

private void importCollection() {
    // Fetch text file
    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    intent.setType("text/*");
    startActivityForResult(intent, IMPORT_COLLECTION_CODE);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (data != null) {
        if (requestCode == IMPORT_COLLECTION_CODE) {
            // Fetch elements
            Uri uri = data.getData();

            StringBuilder sb = new StringBuilder();

            BufferedReader bufferedReader = null;

            try {
                ParcelFileDescriptor pfd = getContentResolver().
                        openFileDescriptor(uri, "r");
                BufferedReader bufferedReader =
                        new BufferedReader(new FileReader(pfd.getFileDescriptor()));

                String line;

                while((line = bufferedReader.readLine()) != null) { // <-- Exception here
                    sb.append(line);
                    sb.append("\n");
                }

                // ... do something with sb
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if(bufferedReader != null) {
                        bufferedReader.close();
                    }
                } catch(IOException e) {
                    // ignore
                }
            }
        }
    }
}

我還嘗試將讀取文件的代碼放入AsyncTask中(無論如何是個好主意),並將FileReader直接傳遞給gson的fromJson方法,但是我仍然遇到相同的錯誤。

在StackOverflow上報告了一些類似的案例,在這些案例中,人們在讀取更多數據之前不小心關閉了閱讀器,但是我的代碼中不是這種情況。

我的明顯問題是:是否有人知道為什么會發生這種情況和/或解決方法?

greenapps在評論中回答了我的問題: 在官方文檔之后,我應該使用InputStream:

    InputStream inputStream = getContentResolver().openInputStream(uri);
BufferedReader reader = new BufferedReader(new InputStreamReader(
        inputStream));

然后就可以正常工作了。

暫無
暫無

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

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