Developer Tip #6: Programmatically Reading and Writing From SD Card

Here’s a little low-level tutorial that I think will make your lives easier.  What the use in enabling your SD card in a development environment, if you don’t know how to read / write to said drive?  Well have no fear.  Here’s a condensed, simple method for doing just that.

private void WriteToFile(String what_to_write) {
        try{
            /* Environment.getExternalStorage Directory calls the SDCard’s filepath, which may change per device */
            File root = Environment.getExternalStorageDirectory();
            //if we have permission to write to this drive…
            if(root.canWrite()){
                File dir = new File(root + "where_on_the_SDCard_do_you_want_to_write");
                //
                File datafile = new File(dir, number + ".extension");
                FileWriter datawriter = new FileWriter(datafile);
                BufferedWriter out = new BufferedWriter(datawriter);
                // More likely is going to be a loop that writes consecutive entries of data
                out.write(what_to_write);
                //remember to close what you open…
                out.close();
            }
        }catch(IOException e){
            Log.e("Whoops", "Can’t write" + e.getMessage());
        }
    }

Ok… now that we can write to file… how about reading from that file?  See below:

/*calling SD drive… you can replace w/ whatever path you want */
File f = new File(Environment.getExternalStorageDirectory().getPath() + "your_path" + ".your_extension");
FileInputStream fileIS = new FileInputStream(f);
BufferedReader buf = new BufferedReader(new InputStreamReader(fileIS));
String read = new String();
while((read = buf.readLine())!= null){
    //Do Something Which each line of data read
    parse(read);
}