Android:将Bytearray写入文件
我正在尝试编写从服务器接收到的 byteArray。这是我的代码
private fun writePdf(content: ByteArray) {
val storageDir = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
val file = File("${storageDir?.path}/", "${Date().time}Download.pdf")
try {
// file.writeBytes(archivo)
val os = FileOutputStream(file, false)
os.write(content)
os.flush()
os.close()
} catch (e: IOException) {
e.printStackTrace()
}
val intent = Intent(Intent.ACTION_VIEW)
val uri = FileProvider
.getUriForFile(
this,
this.packageName + ".fileprovider",
file)
intent.setDataAndType(uri, "application/pdf")
intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
try{
startActivity(intent)
}catch (e: Exception){
e.printStackTrace()
Toast.makeText(this, "Error", Toast.LENGTH_LONG)
.show()
}
}
问题是,当pdf打开时它是空白的,就像什么也没写一样。
- 我尝试过使用 FileOutputStream 和 File.writeBytes 进行写入。
- 我已经检查了 byteArray(以防损坏或其他问题),它没有问题。
- 我在写入之前和之后检查了文件的length(),它的长度相应增加。
谢谢,感谢任何形式的帮助。
I'm trying to write a byteArray received from a server. This is my code
private fun writePdf(content: ByteArray) {
val storageDir = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
val file = File("${storageDir?.path}/", "${Date().time}Download.pdf")
try {
// file.writeBytes(archivo)
val os = FileOutputStream(file, false)
os.write(content)
os.flush()
os.close()
} catch (e: IOException) {
e.printStackTrace()
}
val intent = Intent(Intent.ACTION_VIEW)
val uri = FileProvider
.getUriForFile(
this,
this.packageName + ".fileprovider",
file)
intent.setDataAndType(uri, "application/pdf")
intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
try{
startActivity(intent)
}catch (e: Exception){
e.printStackTrace()
Toast.makeText(this, "Error", Toast.LENGTH_LONG)
.show()
}
}
The problem is that when the pdf opens it is blank, like nothing has been written.
- I've tried writing with FileOutputStream and File.writeBytes.
- I've checked the byteArray (in case is corrupted or something) and it has no problems.
- I've checked the length() of the file before and after writing, and it's length increases accordingly.
Thanks, any kind of help is appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我终于找到了问题所在,并解决了。上面的代码一切正常;问题是用于可视化 PDF 的意图的标志是错误的。而不是:
应该是:
I finally found the problem, and solution. Everything with the code above was okay; the problem was that the flags for the intent to visualize the PDF were wrong. Instead of:
It should be: