FileWriter in Android

      6 Comments on 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(“sdcardfilename.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 “datadatacomyourpackagefilename.txt” which would create a file in the data directory of your package.

6 thoughts on “FileWriter in Android

  1. Anonymous

    What about file permission, how do you set it so that another process/user can access? Using:
    openFileOutput(FileName, "MODE_WORLD_READABLE");
    could be used, and sets the permission.
    I am not sure how to use FilePermission(FileName, string action); sting="read", "read write"?????

  2. Anonymous

    That is the best example I've been able to find for weeks!!!! Clear, Simple and easily expandable.

    Point I'll make… for:

    FileWriter("sdcardfilename.txt");

    I had to escape the backslashes otherwise it treated them as escape characters:

    FileWriter("\sdcard\filename.txt");

    Thank you, you're a legend.

  3. Dan

    You should be using "/" not "" anyways because Android Apps runs on Linux. An even more correct way is to use File.sepearator which will substitude the correct character based on the current system you are running on. But this would be only needed if someone had a version of the delvik machine that ran on a non-linux system.

Leave a Reply