Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - getting from a Uri to an InputStream to a byte array?

Tags:

android

I'm trying to get from an Android Uri to a byte array.

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?

The output is "fileUriString = content://media/external/video/media/53" and "len of data is 61 bytes".

Thanks!

like image 216
AP257 Avatar asked Mar 12 '10 22:03

AP257


People also ask

How do you convert an InputStream to ByteArray in Java?

Example 1: Java Program to Convert InputStream to Byte Arraybyte[] array = stream. readAllBytes(); Here, the readAllBytes() method returns all the data from the stream and stores in the byte array. Note: We have used the Arrays.

How do you write InputStream to ByteArrayOutputStream?

The IOUtils type has a static method to read an InputStream and return a byte[] . InputStream is; byte[] bytes = IOUtils. toByteArray(is); Internally this creates a ByteArrayOutputStream and copies the bytes to the output, then calls toByteArray() .


1 Answers

is.toString() will give you a String representation of the InputStream instance, not its content.

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.


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(); } 
like image 88
brabster Avatar answered Oct 05 '22 03:10

brabster