Skip to content

Instantly share code, notes, and snippets.

@orip
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save orip/d9a61f1622e6808ec2e6 to your computer and use it in GitHub Desktop.
Save orip/d9a61f1622e6808ec2e6 to your computer and use it in GitHub Desktop.
Adapt between Android's Context.openFile{Input,Output} and its mode support, and Guava's sinks and sources.
// Available under the MIT license, http://opensource.org/licenses/MIT
/**
* Adapt between Context's file input/output streams and Guava's sinks and sources.
*
* This supports file modes.
*
* Usage:
* ByteSink sink =
* new AndroidPrivateFileGuavaAdapter(
* "foo", Context.MODE_PRIVATE, context).asByteSink();
*/
public class AndroidPrivateFileGuavaAdapter {
private final String mName;
private final int mMode;
private final Context mContext;
public AndroidPrivateFileHelper(String name, int mode, Context context) {
mName = name;
mMode = mode;
mContext = context.getApplicationContext();
}
public ByteSink asByteSink() {
return new ByteSink() {
public OutputStream openStream() throws IOException {
return mContext.openFileOutput(mName, mMode);
}
};
}
public ByteSource asByteSource() {
return new ByteSource() {
public InputStream openStream() throws IOException {
return mContext.openFileInput(mName);
}
};
}
public CharSink asCharSink() {
return asByteSink().asCharSink(Charsets.UTF_8);
}
public CharSource asCharSource() {
return asByteSource().asCharSource(Charsets.UTF_8);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment