Skip to content

Instantly share code, notes, and snippets.

@mikeplate
Created November 20, 2010 12:00
Show Gist options
  • Save mikeplate/707781 to your computer and use it in GitHub Desktop.
Save mikeplate/707781 to your computer and use it in GitHub Desktop.
Store a single binary value in a file, Java, Android
// This function reads the stored value from a file on the device
void openCount() {
try {
// Open a file and data stream
FileInputStream out = openFileInput("count.bin");
DataInputStream data = new DataInputStream(out);
// Read the binary value from the stream and store in the integer
_count = data.readInt();
// Remember to close the streams
data.close();
out.close();
}
catch (FileNotFoundException err) {
// Ignore this error, since is should just mean that the program is run for the first time
}
catch (IOException err) {
showError(err);
}
}
// This function stores the current value in a file on the device
void saveCount() {
try {
// Open a file and data stream
FileOutputStream out = openFileOutput("count.bin", MODE_PRIVATE);
DataOutputStream data = new DataOutputStream(out);
// Write the binary value of the integer to the stream
data.writeInt(_count);
// Remember to close the streams
data.close();
out.close();
}
catch (FileNotFoundException err) {
showError(err);
}
catch (IOException err) {
showError(err);
}
}
// This function is called to show the error message of an exception in an alert dialog
void showError(Exception err) {
String msg = getString(R.string.file_error, err.getLocalizedMessage());
new AlertDialog.Builder(this).setMessage(msg).show();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment