• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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

 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Bartender
Posts: 9626
16
Mac OS X Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
java.io.ObjectOutputStream
 
Michael Martinez
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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: 9626
16
Mac OS X Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic