If you're using files to pass data around between different components of a system it may make sense to use Thrift. Doing so means you get smaller file sizes (assuming you do binary serialization) but still have files that can be easily read in many programming languages.
In Java, writing Thrift objects to disk is straightforward. Here's a utility class that I use for doing so:
importjava.io.BufferedOutputStream;importjava.io.File;importjava.io.FileNotFoundException;importjava.io.FileOutputStream;importjava.io.IOException;importcom.facebook.thrift.TBase;importcom.facebook.thrift.TException;importcom.facebook.thrift.protocol.TBinaryProtocol;importcom.facebook.thrift.transport.TIOStreamTransport;/**
* Simple class that makes it easy to write Thrift objects to disk.
* @author Joel Meyer
*/publicclassThriftWriter{/** File to write to. */protectedfinalFilefile;/** For writing to the file. */privateBufferedOutputStreambufferedOut;/** For binary serialization of objects. */privateTBinaryProtocolbinaryOut;/**
* Constructor.
*/publicThriftWriter(Filefile){this.file=file;}/**
* Open the file for writing.
*/publicvoidopen()throwsFileNotFoundException{bufferedOut=newBufferedOutputStream(newFileOutputStream(file),2048);binaryOut=newTBinaryProtocol(newTIOStreamTransport(bufferedOut));}/**
* Write the object to disk.
*/publicvoidwrite(TBaset)throwsIOException{try{t.write(binaryOut);bufferedOut.flush();}catch(TExceptione){thrownewIOException(e);}}/**
* Close the file stream.
*/publicvoidclose()throwsIOException{bufferedOut.close();}}
If you have a Thrift object called Album and you'd like to write a list of them to file you'd do it like so:
// Create writer
ThriftWriterthriftOut=newThriftWriter(newFile("/some/thrift/file.thrifty"));// Open writer
thriftOut.open();// Write the objects to disk
for(Albumalbum:albums){thriftOut.write(album);}// Close the writer
thriftOut.close();
ThriftWriter uses the interface com.facebook.thrift.TBase, which defines the methods needed for reading and writing a Thrift object to a Thrift protocol. We could use a single ThriftWriter to write any number of different objects to disk, since they all implement TBase, but then you'd have to make sure you knew what order the objects came in when reading the file.
comments powered by Disqus