Thursday, July 12, 2012

Android - reading and writing files

Playing around with Android these days and it turns out for simple file I/O I had to search around a bit. Here is my code reading/writing some simple JSON. Hope it helps you out!
private void writeToFile(String jsonString) {
  Log.d(TAG, "Writing JSON to file: " + jsonString);
  try {
   FileOutputStream fos = context.openFileOutput(FILENAME,     Context.MODE_PRIVATE);
   OutputStreamWriter osw = new OutputStreamWriter(fos);


  } catch (FileNotFoundException e) {
   throw new WorldClockException(e);
  } catch (IOException e) {
   throw new WorldClockException(e);

Open the file in private mode - only owning application may read/write to such a file. Write the string, flush and close.

The close() should ideally be in a finally block but I'm still trying to figure out Android so this is not perfect!

Part of my bigger WorldClock project at GitHub if you are interested to contribute!

No comments: