Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FileInputStream to byte array in Android application

Tags:

java

android

I have a FileInputStream created using Context.openFileInput(). I now want to convert the file into a byte array.

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.

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.

like image 421
Jeremy Lee Avatar asked Mar 17 '11 01:03

Jeremy Lee


People also ask

What is FileInputStream and Fileoutputstream in selenium?

InputStream − This is used to read (sequential) data from a source. OutputStream − This is used to write data to a destination.

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() .

What is FileInputStream Android studio?

A FileInputStream obtains input bytes from a file in a file system. What files are available depends on the host environment. FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader .


1 Answers

This should work.

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();
like image 172
Robby Pond Avatar answered Oct 06 '22 09:10

Robby Pond