A good way to write an array of shorts to a file with LittleEndian

I have a short [512x512] array that needs to be written to a binary with a bit of endian . I know how to write one short file with a little endian . I think there are better ways than looping through an array writing one after the other .

+3
source share
2 answers

Somewhat:

short[] payload = {1,2,3,4,5,6,7,8,9,0};
ByteBuffer myByteBuffer = ByteBuffer.allocate(20);
myByteBuffer.order(ByteOrder.LITTLE_ENDIAN);

ShortBuffer myShortBuffer = myByteBuffer.asShortBuffer();
myShortBuffer.put(payload);

FileChannel out = new FileOutputStream("sample.bin").getChannel();
out.write(myByteBuffer);
out.close();

And somewhat like this, to get it back:

ByteBuffer myByteBuffer = ByteBuffer.allocate(20);
myByteBuffer.order(ByteOrder.LITTLE_ENDIAN);
FileChannel in = new FileInputStream("sample.bin").getChannel();
in.read(myByteBuffer);
myByteBuffer.flip();


ShortBuffer myShortBuffer = myByteBuffer.asShortBuffer();
myShortBuffer.get(payload);
System.out.println(Arrays.toString(payload));
+7
source

, , ByteBuffer . ByteBuffer FileChannel.

ByteBuffer .order().

+3

All Articles