Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Can I use ByteBuffer and InputStream together?  RSS feed

 
Tom Katz
Ranch Hand
Posts: 169
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There's some existing code that reads in a file, creating a ByteBuffer from file's byte[]. The ByteOrder is set to LITTLE_ENDIAN and getInt correctly gets the expected header constants from the file, etc. Everything works.

I'd like to change this because we end up having to instantiate a byte[] for the whole file this way. I'd like to open a stream to the file and be able to read those ints in the correct byte order.

SO, I'm trying to find a way to read from an InputStream and use a ByteBuffer of what I read to do the same as the original code.

I've seen several classes online that are basically Little Endian versions of DataInputStream, but am hoping there's another way that I haven't thought of.

I hope I've explained myself clearly.. thanks in advance for any help!

Tom
 
Nitesh Kant
Bartender
Posts: 1638
IntelliJ IDE Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Tom:
SO, I'm trying to find a way to read from an InputStream and use a ByteBuffer of what I read to do the same as the original code.

Okie, so where are you stuck?
You can get a FileChannel from the FileInputStream using getChannel() method.
Once you get the channel, you can use different flavors of read() to populate the channel contents in the buffer.
While allocating the buffer, you can set the Byte order using order() method.
 
Tom Katz
Ranch Hand
Posts: 169
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the ideas. And actually, one of the first things I tried (reading a set amount of bytes from the stream and creating a ByteBuffer from that) ended up working as I needed it to.

Part of the problem, that had me thinking my initial attempts weren't working, was due to an extra 8 bytes at the front of the file from having uploaded it from a JSP. Once I a skipped those, my code worked.
 
Tom Katz
Ranch Hand
Posts: 169
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Actually, those 8 bytes weren't from the file upload at all, please disregard. I was suffering from head-up-my-a** syndrome.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!