Android的 - 从一个URI来获得一个InputStream字节数组? [英] Android - getting from a Uri to an InputStream to a byte array?
问题描述
我想从Android的开放的我们得到一个字节数组。
I'm trying to get from an Android Uri to a byte array.
我有以下的code,但它一直告诉我的字节数组是61字节长,即使该文件是相当大的 - 所以我认为这可能会开启乌里字符串成字节数组,而不是文件:(
I have the following code, but it keeps telling me that the byte array is 61 bytes long, even though the file is quite large - so I think it may be turning the Uri string into a byte array, rather than the file :(
Log.d(LOG_TAG, "fileUriString = " + fileUriString);
Uri tempuri = Uri.parse(fileUriString);
InputStream is = cR.openInputStream(tempuri);
String str=is.toString();
byte[] b3=str.getBytes();
Log.d(LOG_TAG, "len of data is " + imageByteArray.length
+ " bytes");
请有人可以帮我找出该怎么办?
Please can someone help me work out what to do?
输出为fileUriString =内容://媒体/外部/视频/媒体/ 53和数据len为61字节
The output is "fileUriString = content://media/external/video/media/53" and "len of data is 61 bytes".
谢谢!
推荐答案
is.toString()
会给你的InputStream实例的字符串再presentation,而不是它的内容。
is.toString()
will give you a String representation of the InputStream instance, not its content.
您需要阅读()从InputStream到您的字节数组。有两个读的方法来做到这一点,阅读()可以阅读一次一个字节,和<一href="http://developer.android.com/reference/java/io/InputStream.html#read%28byte%5b%5d%29">read(byte[]字节)读取从InputStream字节为你传递给它的字节数组。
You need to read() bytes from the InputStream into your array. There's two read methods to do that, read() which reads a single byte at a time, and read(byte[] bytes) which reads bytes from the InputStream into the byte array you pass to it.
更新:阅读给定了一个InputStream不具有长度为这样的字节,则需要读取的字节中,直到有一无所有。我建议创建一个方法,为自己喜欢的东西,这是一个很好的简单的起点(这就是我至少会做到这一点在Java中)。
Update: to read the bytes given that an InputStream does not have a length as such, you need to read the bytes until there is nothing left. I suggest creating a method for yourself something like this is a nice simple starting point (this is how I would do it in Java at least).
public byte[] readBytes(InputStream inputStream) throws IOException {
// this dynamically extends to take the bytes you read
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
// this is storage overwritten on each iteration with bytes
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
// we need to know how may bytes were read to write them to the byteBuffer
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
// and then we can return your byte array.
return byteBuffer.toByteArray();
}
这篇关于Android的 - 从一个URI来获得一个InputStream字节数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!