问题描述
我有一个FileInputStream创建使用 Context.openFileInput()
。我现在想将文件转换为字节数组。
I have a FileInputStream created using Context.openFileInput()
. I now want to convert the file into a byte array.
不幸的是,我不能确定所需的字节数组FileInputStream.read(字节[])的尺寸
。该用()
方法是行不通的,而我不能创建一个文件来检查它的使用的具体路径长度,可能是因为路径是无法访问到非root用户。
Unfortunately, I can't determine the size of the byte array required for FileInputStream.read(byte[])
. The available()
method doesn't work, and I can't create a File to check it's length using the specific pathname, probably because the path is inaccessible to non-root users.
我读 ByteArrayOutputStream
,它似乎动态调整字节数组大小要合适,但我不能得到如何从的FileInputStream 写入 ByteArrayOutputStream
。
I read about ByteArrayOutputStream
, and it seems to dynamically adjust the byte array size to fit, but I can't get how to read from the FileInputStream
to write to the ByteArrayOutputStream
.
推荐答案
这应该工作。
InputStream is = Context.openFileInput(someFileName);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
while ((int bytesRead = is.read(b)) != -1) {
bos.write(b, 0, bytesRead);
}
byte[] bytes = bos.toByteArray();
这篇关于的FileInputStream以字节数组中的Android应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!