• Post Reply Bookmark Topic Watch Topic
  • New Topic

read/write integer binary file into integer array -- how?  RSS feed

 
Michael Martinez
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is the quickest way to read a binary file of 4-byte integers into an integer array? And also the quickest way to write an integer array into a binary file?

In order to read, I was thinking something like this would work:

... read file into byteArray ...
int[] intArray = ((ByteBuffer.wrap(byteArray)).asIntBuffer()).array();

But I can't find anything analogous to asIntBuffer() to go back to a byte array for writing (such as something like asByteBuffer() in the IntBuffer class).

Is there a way to directly read/write from a file to an integer array and vice versa?
 
Joe Ess
Bartender
Posts: 9426
12
Linux Mac OS X Windows
 
Michael Martinez
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, although I'm not sure I understand your suggestion. Maybe this isn't really an I/O issue after all; I can read and write the file just fine as a byte array. But internally the data needs to be represented as an integer array. So how to efficiently convert a large integer array to and from a byte array is what I need... like if there was a way to cast between array types.
 
Joe Ess
Bartender
Posts: 9426
12
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I thought this was the question:

Is there a way to directly read/write from a file to an integer array and vice versa?

You can do that with Object*putStreams.
As for converting between primitive arrays, there's no way directly "cast" them. You need to create a new array of the type and size required and copy the values. System.arraycopy() can do the copy for you.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!