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.

6 comments:

  1. 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"?????

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

    Point I'll make... for:

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

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

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


    Thank you, you're a legend.

    ReplyDelete
  3. 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.

    ReplyDelete
  4. Hello Bibek ; from Apro.

    ReplyDelete
  5. I get an exception thrown with the message permission denied. How does one set the permissions in the example above ?

    ReplyDelete
  6. In the manifest file:

    ReplyDelete