File I/O
Use the standard Java ObjectOutputStream and ObjectInputStream objects to write and read data to a file in the app's data area. The code below writes an object that is referenced with the ref reference variable (and context reference's the Activity's context). Here we'll make ref refer to an ArrayList of String objects, although the object could of any class that implements the Serializable interface.
public static final String filename = "my_data.dat"; private static final String TAG = "*** YOUR TAG ***"; ArrayList<String> ref = new ArrayList<String>(); // Fill the array list with values here... ... FileOutputStream fos; ObjectOutputStream os; try { fos = getApplicationContext().openFileOutput(filename, Context.MODE_PRIVATE); os = new ObjectOutputStream(fos); os.writeObject(ref); os.flush(); os.close(); } catch (FileNotFoundException e) { Log.d(TAG, "Error when saving: " + e); } catch (IOException e) { Log.d(TAG, "Error when saving: " + e); }
To later restore the object to a reference named newRef:
FileInputStream fis; ObjectInputStream is; ArrayList<String> newRef; // empty reference -- this will get filled with readObject, below try { fis = getApplicationContext().openFileInput(filename); is = new ObjectInputStream(fis); newRef = (ArrayList<String>) is.readObject(); is.close(); } catch (FileNotFoundException e) { Log.d(TAG, "Error when restoring: " + e); } catch (IOException e) { Log.d(TAG, "Error when restoring: " + e); } catch (ClassNotFoundException e) { Log.d(TAG, "Error when restoring: " + e); }
The file will be stored in the folder /data/data/package_name/files/file_name. To find the file, start the app in the debugger in eclipse, then switch to the DDMS perspective, open the File Explorer window within DDMS, then navigate to /data/data/package_name/files/file_name.