In Java, when I write to a file with a DataOutputStream, how do I determine the endian of the data being written?

I use a DataOutputStream to write to a file, however I want to change the endian of the data.

This is how I write byte data to a file (by default it is output by default by default)

 public void generateBinObjFile(String outputFile) try { // Create file DataOutputStream stream = new DataOutputStream( new FileOutputStream(outputFile)); stream.writeShort(this.quantize(this.xComponents.get(index), //<-- Short is written in little Endian this.min_x, this.max_x) - 32768); } // catch statements here 

Is there a way to define Endian how byte data is written in Java?

+6
source share
5 answers

You cannot do this with a DataOutputStream , which always uses a large endian.

You can use the ByteBuffer , which you can call order() to influence how it reads and writes data.

You can use ByteBuffer either to prepare the byte[] , which you will write with the classic OutputStream later, or completely switch to NIO and use any WritableByteChannel to write

+8
source

You cannot :

Records a brief description of the underlying output stream as two bytes with a high byte.

All multi-byte methods work like this. If you need it the other way around, you need to write bytes yourself.

0
source

It outputs data in a manner that is read by DataInputStream.

If you need to worry about content, you should not use Data * Stream.

0
source

All answers are given correctly. However, you can take the source of DataOutputStream, insert it into a new class and reverse the byte order in different writeShort, writeLong, etc. (Or at least the ones you need). This is not such a difficult job.

Obviously, you cannot use it to communicate with a DataInputStream on the other hand, but I suppose you need to write to a file or socket with a program on the other side, so you do not need a DataInputStream.

0
source

Source: https://habr.com/ru/post/894808/


All Articles