How to write large byte ByteBuffer to small byte in Java
I currently have a Java ByteBuffer, which already has data in big endian format Then I want to write a binary file as little endian
This is the code for writing files in big endian:
public void writeBinFile(String fileName,boolean append) throws FileNotFoundException,IOException { FileOutputStream outStream = null; try { outStream = new FileOutputStream(fileName,append); FileChannel out = outStream.getChannel(); byteBuff.position(byteBuff.capacity()); byteBuff.flip(); byteBuff.order(ByteOrder.LITTLE_ENDIAN); out.write(byteBuff); } finally { if (outStream != null) { outStream.close(); } } }
Note that ByteBuffer is a ByteBuffer filled in big endian format
My last method is to create another buffer and set ByteBuffer to little endian, then read the "getInt" value from the original (big endian) buffer and set the value "setint" to little endian buffer I think there is a better way
Solution
Endianness has no meaning for byte [] Endianness is only applicable to multi byte data types, such as short, int, long, float, or double The correct time to get the correct end is to write the original data to the byte and read the actual format
If byte [] is given, the original data types must be decoded and re encoded using a different byte order I'm sure you will agree that this is a) not easy to do or ideal b) not automatic