Wednesday, April 20, 2011

How to save a Java FloatBuffer (or any Buffer) to a file

I have a FloatBuffer of known size and just want to dump the data to a file (in binary) for inspection outside my app. What's the easiest way to do this?

From stackoverflow
  • UPDATE FOR BINARY OUTPUT:

    // There are dependencies on how you create your floatbuffer for this to work
    // I suggest starting with a byte buffer and using asFloatBuffer() when
    // you need it as floats.
    // ByteBuffer b = ByteBuffer.allocate(somesize);
    // FloatBuffer fb = b.asFloatBuffer();
    // There will also be endiance issues when you write binary since
    // java is big-endian. You can adjust this with Buffer.order(...)
    // b.order(ByteOrder.LITTLE_ENDIAN)
    // If you're using a hex-editor you'll probably want little endian output
    // since most consumer machines (unless you've got a sparc / old mac) are little
    
    
    FileOutputStream fos = new FileOutputStream("some_binary_output_file_name");
    FileChannel channel = fos.getChannel();
    
    channel.write(byteBufferBackingYourFloatBuffer);
    
    fos.close();
    

    TEXT OUTPUT: Since you want this to be viewable I assume you want a text file. You'll want to use a PrintStream.

    // Try-catch omitted for simplicity
    
    PrintStream ps = new PrintStream("some_output_file.txt");
    for(int i = 0; i < yourFloatBuffer.capacity(); i++)
    {
       // put each float on one line
       // use printf to get fancy (decimal places, etc)
       ps.println(yourFloagBuffer.get(i));
    }
    
    ps.close();
    

    Didn't have time to post a full raw/binary (non-text) version of this. If you want to do that use a FileOutputStream, get the FileChannel, and directly write the FloatBuffer (since it's a ByteBuffer)

    jblocksom : Thanks, although actually I did want to write it all out in binary. Sorry to not be specific about that, I'll update the question.
  • This iterates through the array backed by your buffer and outputs each float. Just replace the text file and floatBuffer with your own parameters.

    PrintStream out = new PrintStream("target.txt");
    for(float f : floatBuffer.array()){
      out.println(f);
    }
    out.close();
    
  • Asusming you want the data as binary:

    Start with a ByteBuffer. Call asFloatBuffer to get your FloatBuffer. When you've finished doing your stuff, save the ByteBuffer out to a WritableByteChannel.

    If you already have FloatBuffer it can be copied into the buffer from step 2 with a put.

    A low performance but easier way would be to use Float.floatToIntBit.

    (Watch for endianess, obviously.)

0 comments:

Post a Comment