Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
564 views
in Technique[技术] by (71.8m points)

io - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...