在 Java 中,使用 DataOutputStream 写入文件时,如何定义正在写入的数据的 Endian? [英] In Java, when writing to a file with DataOutputStream, how do I define the Endian of the data being written?
问题描述
我正在使用 DataOutputStream
写入文件,但是我想更改数据的字节序.
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
有没有一种方法可以定义字节数据在 Java 中的写入方式?
Is there a way i can define the Endian of how byte data is written in Java?
推荐答案
你不能用 DataOutputStream
做到这一点,它总是使用大端.
You can not do this with DataOutputStream
, which always uses big endian.
您可以使用ByteBuffer
,您可以在其上调用 order()
来影响它如何读取和写入数据.
You can use a ByteBuffer
on which you can call order()
to influence how it reads and writes data.
您可以使用 ByteBuffer
either 来准备一个 byte[]
,您将使用经典的 OutputStream
编写该byte[]
code> 稍后或完全转到 NIO 并使用任何WritableByteChannel
用于写入
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
这篇关于在 Java 中,使用 DataOutputStream 写入文件时,如何定义正在写入的数据的 Endian?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!