使用LittleEndian将短裤数组写入文件的好方法

时间:2012-05-08 20:43:02

标签: java

我有短[512x512]数组需要使用小端写入二进制文件。我知道如何用 little endian 一个短文件。我认为可能有更好的方式而不是循环编写逐个的数组。

2 个答案:

答案 0 :(得分:7)

有点像这样:

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();

有点像这样才能找回来:

ByteBuffer myByteBuffer = ByteBuffer.allocate(20);
myByteBuffer.order(ByteOrder.LITTLE_ENDIAN);
FileChannel in = new FileInputStream("sample.bin").getChannel();
in.read(myByteBuffer);
myByteBuffer.flip();
in.close(); // do not forget to close the channel

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

答案 1 :(得分:3)

如果确实需要快速,那么最好的解决方案是将短路放入ByteBuffer,并且字节顺序很小。然后,使用FileChannel在一个操作中编写ByteBuffer。

使用ByteBuffer方法设置.order()的字节顺序。

相关问题