使用contentResolver将docx转换为Base64会在Android上提供不可读的格式

问题描述 投票:0回答:1

我有一个文件test.docx包含1个单词“Testing”。此文件位于我的Dropbox文件夹中,我使用contentResolver在App中打开它。

enter image description here

码:

            val inputStream = context.contentResolver.openInputStream(uri)
            val allText = inputStream.bufferedReader().use(BufferedReader::readText)
            base64Image = Base64.encodeToString(allText.toByteArray(), Base64.NO_WRAP)

allText会返回一些数据,但是当把它放在文本文件中并将其保存为.docx时我无法查看它,它已经坏了。我想我应该在bufferedReader方法中添加一个Charset。尝试了一对,但没有一个工作。

什么应该是正确的代码?

android kotlin android-contentresolver
1个回答
1
投票

DOCX不是纯文本。它是二进制格式。使用readBytes()读取字节:

val bytes = context.contentResolver.openInputStream(uri).readBytes()

请记住,您的应用程序将崩溃与OutOfMemoryError大内容。请重新考虑您的计划以阅读整个内容,更不用说将其转换为base64。

© www.soinside.com 2019 - 2024. All rights reserved.