Thursday, August 13, 2009

FileWriter in Android

This is a pretty handy API that you can use to write a string of information to a file on the device. It doesn’t need a StreamWriter or BufferedWriter or FileOutputStream. It is short and sweet.
            FileWriter fWriter;
            try{
                 fWriter = new FileWriter(“\sdcard\filename.txt”);
                 fWriter.write(yourString);
                 fWriter.flush();
                 fWriter.close();
             }catch(Exception e){
                      e.printStackTrace();
             }
The flush() and close() calls are important here, and also make sure that the “sdcard” is mounted. Else, you can use a path such as “data\data\com\yourpackage\filename.txt” which would create a file in the data directory of your package.