微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

我正在尝试在sdcard中获取文档的一个字节。我的工作正好是以下内容

1-)我选择文件

   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-)我现在有一个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<>();

在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;
}

在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转换为字节数组: Convert InputStream to byte array in Java

但是,根据您需要对字节做些什么,您可以直接使用流。例如,如果您要转换PDF,则可以使用LEADTOOLS CloudServices库: https://www.leadtools.com/support/forum/posts/t12369-

,
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,bytes.length);
    buf.close();
} catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

来源:Android : How to read file in bytes?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。