File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes I/O and Streams and the fly likes Reading file into byte array Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Java » I/O and Streams
Reply Bookmark "Reading file into byte array" Watch "Reading file into byte array" New topic
Author

Reading file into byte array

Tom Eric
Greenhorn

Joined: Nov 03, 2003
Posts: 9
Hi,
How do I read file into byte array?
Is there any method other than reading each character and write into byte array.
Right now I am using the following code ..
Is there any efficient way to read file into byte array ?
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(args[0]));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int c;
while ((c = bis.read()) > -1) {
baos.write(c);
}
bis.close();
byte[] buf = baos.toByteArray();

Thanks,
Tom.
jason adam
Chicken Farmer ()
Ranch Hand

Joined: May 08, 2001
Posts: 1927
In the nio.channels there is a FileChannel class that you can use to get a MappedByteBuffer, which has a method called array that will return a byte array. I believe the nio stuff is very effecient (someone with a lot of experience using it may want to speak up here).
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18641
The NIO stuff can be much more efficient than traditional I/O, but not always; sometimes it may even be slower. A MappedByteBuffer is most applicable for a large file you need to access multiple times. You may also find a regular ByteBuffer to be useful, using FileChannel's read(ByteBuffer) method.
However you can also get better performance than you do currently using tradional I/O. Specifically, you can read directly into a byte array, rather than reading one byte at a time and transferring to an intermediate object like BAOS. Try something like:

The loop is necessary because read(byte[], int, int) isn't guaranteed to read all requested bytes at once. But it generally reads a lot of bytes at once, which is more efficient than a bunch of separate reads. And in this case you don't need the BufferedInputStream - the destination array is your buffer. I don't believe you can make this operation any more efficient using tradional I/O.


"I'm not back." - Bill Harding, Twister
 
 
subject: Reading file into byte array
 
Two Laptop Bag