Java Android-如何从SD卡获取文件字节

Java Android-如何从SD卡获取文件字节,java,android,android-studio,kotlin,illegalargumentexception,Java,Android,Android Studio,Kotlin,Illegalargumentexception,我正试图从SD卡中获取文档的一个字节。我所做的就是: 1-)我选择文件 fun openFile() { val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply { addCategory(Intent.CATEGORY_OPENABLE) type = "application/pdf" } startActivityForResult(intent, PIC

我正试图从SD卡中获取文档的一个字节。我所做的就是:

1-)我选择文件

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

2-)我现在有了一个URI。我想把它转换成一个文件。然后我尝试获取字节

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.
        }
    }
}
但这个错误:

 Caused by: java.lang.IllegalArgumentException: Uri lacks 'file' scheme: 
 content://com.android.externalstorage.documents/document/primary%3ADCIM%2Ftest.pdf

考虑将文件加载为使用TaskCompletionSource异步加载的输入流:

TaskCompletionSource<Stream> tcs = new TaskCompletionSource<>();
在onActivityResult中:

if (requestCode == PICK_PDF_FILE && resultCode == Activity.RESULT_OK) {
   Uri uri = data.getData();
   tcs.setResult().getContentResolver().openInputStream(uri); 
}
else {
   tcs.setResult(null);
}
获得InputStream后,可以将InputStream转换为字节数组:

但是,根据您需要对字节执行的操作,您可以直接使用流。例如,如果您希望转换PDF,可以使用LEADTOOLS CloudServices库:

资料来源:

if (requestCode == PICK_PDF_FILE && resultCode == Activity.RESULT_OK) {
   Uri uri = data.getData();
   tcs.setResult().getContentResolver().openInputStream(uri); 
}
else {
   tcs.setResult(null);
}
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();
}