Thursday, February 16, 2012

Java little endian IO gotcha

Java's goal has been to provide developers with a language that is cross platform, write once run everywhere. To do this Java handles many platform details for you. But sometimes those details are important. Here is an example, I needed to output a TIFF using little-endian byte ordering regardless of what platform the Java code was running on.

import java.io.FileOutputStream;

byte[] imgData = //create the image data using JAI;
String filename = "platform-endian.tiff";

FileOutputStream fos = new FileOutputStream(filename);
fos.write(imgData);
fos.close();

My code would work fine on platforms with Intel or x86 architecture which is little-endian byte order, but when I moved my code to a Solaris system running a SPARC processor, my code started outputting in big-endian TIFFs. This is due to the fact that FileOutputStream hides some of the complexity involved with writing data out to disk. Hiding this complexity is fantastic if all you care about are outputting TIFFs that are byte-order-compatible with the environment your Java code is running in; which is what you would want in 99% of the use cases for creating TIFFs programmatically. But this feature of Java is very bad when you always need little-endian TIFFs at all times. I need little-endian because it is a Federal Reserve regulations are that the TIFFs I make be little-endian.

Thankfully there is a way to force Java to use a specific byte ordering. Use ByteBuffer.

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.FileChannel;
import java.io.FileOutputStream;

byte[] imgData = //create the image data using JAI;
String filename = "little-endian.tiff";

ByteBuffer buffer = ByteBuffer.allocate(imgData.length);
buffer.order(ByteOrder.LITTLE_ENDIAN);
buffer.put(imgData);
out = new FileOutputStream(filename).getChannel();
out.write(buffer);

This code will output directly in little-endian regardless of the architecture of the system running the code.


About Me

My photo
Lead Java Developer Husband and Father

Tags