Sunday, July 13, 2014

Guava's I/O Sources and Sinks on Android

I love Guava's I/O wrappers - ByteSource, ByteSink, CharSource, and CharSink. They encapsulate I/O stream (or reader/writer) access in a way that makes it easy for me to open & close the stream in the same location; when I pass a stream directly, the points of opening it and reliably closing it may be far apart. They also have helper methods to sweeten some common tasks, like reading an entire char source.

Android provides an existing mechanism for accessing private files while controlling their access modes: Context.openFileOutput and Context.openFileInput. As a Source/Sink primer, here's a cool way to adapt between the two:

The usage would look like this:
AndroidPrivateFileGuavaAdapter adapter =
  new AndroidPrivateFileGuavaAdapter("filename", Context.MODE_PRIVATE, context);

 // Read all text
String contents = adapter.asCharSource().read();

 // Write some bytes
byte[] bytes = ...; // obtains bytes from somewhere