In Java, when writing to a file with DataOutputStream, how do I define the Endian of the data being written?

白昼怎懂夜的黑 提交于 2019-12-19 15:05:09

问题


I'm using DataOutputStream to write to a file, however I want to change the endian of the data.

This is how i'm writing the byte data to the file (it outputs in Little endian 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 i can define the Endian of how byte data is written in Java?


回答1:


You can not do this with DataOutputStream, which always uses big endian.

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

You can use the ByteBuffer either to prepare a byte[] that you'll write with a classical OutputStream later on or go entirely to NIO and use any WritableByteChannel for the writing




回答2:


You can use: com.google.common.io.LittleEndianDataOutputStream from

https://google.github.io/guava/releases/17.0/api/docs/com/google/common/io/LittleEndianDataOutputStream.html or copy this class: http://www.cafeaulait.org/books/javaio/ioexamples/07/LittleEndianOutputStream.java




回答3:


You cannot:

Writes a short to the underlying output stream as two bytes, high byte first.

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




回答4:


It outputs the data in a fashion that is readable by DataInputStream.

If you have to worry about the endianness, you should not be using a Data*Stream.




回答5:


all the given answers are right. You can, however, take the source of DataOutputStream, paste it into a new class, and reverse the order of bytes in the various writeShort, writeLong etc.. (or at least in the ones you need). It is not such a difficult work.

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



来源:https://stackoverflow.com/questions/7024039/in-java-when-writing-to-a-file-with-dataoutputstream-how-do-i-define-the-endia

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!