在Java中将ByteBuffer导出为Little Endian文件

时间:2013-04-18 08:45:33

标签: java import export endianness bytebuffer

我想将ByteBuffer作为Little Endian导出到文件中,但是当我再次读入文件时,我必须将其作为Big Endian读取以获得正确的值。如何以我可以在创建的文件中读取Little Endian并获得正确值的方式导出ByteBuffer?

    //In the ByteBuffer tgxImageData there are the bytes which I want to export and import again, the ByteBuffer is ordered as little endian


    //export ByteBuffer into File
    FileOutputStream fos = new FileOutputStream(outputfile);            
    tgxImageData.position(0);
    byte[] tgxImageDataByte = new byte[tgxImageData.limit()];
    tgxImageData.get(tgxImageDataByte);         
    fos.write(tgxImageDataByte);            
    fos.close();


    //import File into ByteBuffer
    FileInputStream fis2 = new FileInputStream(outputfile);     
    byte [] arr2 = new byte[(int)outputfile.length()];
    fis2.read(arr2);
    fis2.close();           
    ByteBuffer fileData2 = ByteBuffer.wrap(arr2);


    fileData2.order(ByteOrder.LITTLE_ENDIAN);           
    System.out.println(fileData2.getShort(0));          //Wrong output, but here should be right output
    fileData2.order(ByteOrder.BIG_ENDIAN);          
    System.out.println(fileData2.getShort(0));          //Right output, but here should be wrong output

1 个答案:

答案 0 :(得分:0)

这是一个如何将短片写为小端

的示例
    FileOutputStream out = new FileOutputStream("test");
    ByteBuffer bbf = ByteBuffer.allocate(4);
    bbf.order(ByteOrder.LITTLE_ENDIAN);
    bbf.putShort((short)1);
    bbf.putShort((short)2);
    out.write(bbf.array());
    out.close();

您需要在代码中执行类似的操作