title: IOException EBADF (Bad file descriptor) when reading large text files using Intent.ACTION_OPEN_DOCUMENT in Release APK
body: <p>In my android app I provide a menu to import a text file (it contains some Json data that I process later using gson) via Intent.ACTION_OPEN_DOCUMENT. These files can be large, 5 MB or more. </p>
  
  <p>The problem: Everything works when I directly start the app from Android Studio on my phone, also for large files. Yet for the release apk I obtain an IOException EBADF (Bad file descriptor) if the files are larger than around 500kb (the exception is thrown by readLine). This is the case if I read the file from google drive or from Downloads.</p>
  
  <p>I read the code using the following methods (called from my Activity):</p>
  
  <pre><code>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) { // &lt;-- 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
                  }
              }
          }
      }
  }
  </code></pre>
  
  <p>I also tried to put the code that reads the file into an AsyncTask (which is anyways a good idea), and to pass the FileReader to gson's fromJson-method directly, but I still obtain the same error. </p>
  
  <p>There are some similar cases reported on StackOverflow in which people accidentially close the reader before they read more data, yet this is not the case in my code.</p>
  
  <p>My obvious question: Does someone have an idea why this happens and/or a workaround?</p>