3

I'm trying to get a byte of a document inside of sdcard. What I do is exactly the following;

1-) I choose the file.

   fun openFile() {
    val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
        addCategory(Intent.CATEGORY_OPENABLE)
        type = "application/pdf"
    }
    startActivityForResult(intent, PICK_PDF_FILE)
}

enter image description here

2-) I now have a URI. I'm trying to convert it to a file. Then I try to get the bytes.

override fun onActivityResult(requestCode: Int, resultCode: Int, resultData: Intent?) {
    super.onActivityResult(requestCode, resultCode, resultData)

    if (requestCode == PICK_PDF_FILE && resultCode == Activity.RESULT_OK) {
        resultData?.data?.also { documentUri ->
            contentResolver.takePersistableUriPermission(
                documentUri,
                Intent.FLAG_GRANT_READ_URI_PERMISSION
            )
            var file = documentUri.toFile(); // I am trying to convert URI to FILE type. //ERROR LINE
            Log.d("test" , file.readBytes().toString()) // I'm trying to read the bytes.
        }
    }
}

But this error:

 Caused by: java.lang.IllegalArgumentException: Uri lacks 'file' scheme: 
 content://com.android.externalstorage.documents/document/primary%3ADCIM%2Ftest.pdf
Pehr Sibusiso
  • 862
  • 1
  • 14
  • 27

2 Answers2

0

Consider loading the file as an input stream loaded asynchronously using TaskCompletionSource:

TaskCompletionSource<Stream> tcs = new TaskCompletionSource<>();

In openFile():

if (tcs == null || tcs.Task.isCompleted || tcs.Task.isCanceled)
{
   startActivityForResult(Intent.createChooser(intent, "Select Document"), PICK_PDF_FILE);
   return tcs.getTask;
}
else
{
   return tcs.getTask;
}

In onActivityResult:

if (requestCode == PICK_PDF_FILE && resultCode == Activity.RESULT_OK) {
   Uri uri = data.getData();
   tcs.setResult().getContentResolver().openInputStream(uri); 
}
else {
   tcs.setResult(null);
}

Once you have the InputStream, you can then convert the inputStream to a byte array: Convert InputStream to byte array in Java

Depending on what you need to do with the bytes, however, you could just use the stream directly. For example, if you were looking to convert the PDF, you could use the LEADTOOLS CloudServices library: https://www.leadtools.com/support/forum/posts/t12369-

0
File file = new File(path);
int size = (int) file.length();
byte[] bytes = new byte[size];
try {
    BufferedInputStream buf = new BufferedInputStream(new FileInputStream(file));
    buf.read(bytes, 0, bytes.length);
    buf.close();
} catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

source: Android : How to read file in bytes?

youngdero
  • 382
  • 2
  • 16