Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 646
Zeeno Avatar asked Aug 11 '11 10:08

Zeeno


2 Answers

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

like image 98
Joachim Sauer Avatar answered Oct 23 '22 00:10

Joachim Sauer


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

like image 26
codez Avatar answered Oct 23 '22 00:10

codez