The most intelligent Java IDE
[Logo] JavaRanch » JavaRanch Saloon
  Search | FAQ | Recent Topics | Hot Topics
Register / Login


Reply Bookmark it! Watch this topic JavaRanch » Forums » Java » I/O and Streams
 
RSS feed
 
New topic
Author

Reading file into byte array

Tom Eric
Greenhorn

Joined: Nov 03, 2003
Messages: 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
Messages: 1926

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
Messages: 18577

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
 
 
 
Reply Bookmark it! Watch this topic JavaRanch » Forums » Java » I/O and Streams
 
RSS feed
 
New topic
JProfiler
Get rid of your performance problems and memory leaks!