Android @ Kiowok

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.

Image of a file explorer program highlighting the file "jobs.dat", in the "files" folder, in the "com.example.jobsyourname" folder on an Android device.

Read from File via the "raw" Resource Folder

An easy way to bring data into your project is via the res/raw folder. In this example the data will be simple text data, entered into a text file with Notepad.

  • If the raw folder does not already exist, create it (i.e., create the folder res/raw).
  • Use Notepad to create a file with several lines of text. Name the file my_data.txt.
  • Drag and drop my_data.txt into the res/raw folder.
  • Use the code shown below to read and process the text (the loadData method requires that you pass it the application's context):
	private void loadData(Context context) {
        InputStream is = context.getResources().openRawResource(R.raw.my_data);
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr, 8192);

        try {
                 String line = "false";
                 
                 while ((line = br.readLine()) != null) {	
                	 // process this line of input text

                 }
                 
                 isr.close();
                 is.close();
                 br.close();
        } 
        catch (IOException e) {
                 e.printStackTrace();
        }
	}
    

Note that the file name's extension, .txt, is not included as part of the resource id in the call to openRawResource. Sinced the filename is an Android resource it needs to be in all lowercase letters.

If you prefer to use Scanner instead of BufferedReader for pulling input data into your program, the above code can be updated to:

	private void loadData(Context context) {   
   
		try {
			Resources res = context.getResources();
			InputStream is = res.openRawResource(R.raw.roster);
			Scanner scan = new Scanner(is);

			while (scan.hasNext()) {
				// read the file's content with nextLine, nextInt, etc., here
				
			}
			scan.close();
			
		} catch (Exception e) {
			Log.d(TAG, "Exception: " + e);
		}
 	}

 

Top