Grux
Grux

Reputation: 584

Unable to write to file in android

This is driving me insane because it should be working. I'm trying to write two string arraylist to a file. Keep in mind I'm writing to internal storage, so manifest permissions are not the issue here. Here is my code:

File cacheFile = new File(context.getFilesDir(), getChannelFile(s[0]) + ".cache");
if (!cacheFile.exists()) {
    try {
        FileWriter out = new FileWriter(cacheFile);
        for (int i = 0; i < titleArray.size(); i++) {
            Log.d(timesArray.get(i), titleArray.get(i));
            out.write(timesArray.get(i) + "#" + titleArray.get(i));
            out.write(System.getProperty("line.separator"));
        }
        out.close();
        } catch (Exception e) {
            Log.e(Ids.TAG, e.getMessage());
    }
}

Logcat shows exactly what I want to write. But it doesn't write to the file. After this code is executed, my file is created but is 0 bytes. I'm at a loss because there are no exceptions caught and my Log.d shows everything is correct. What am I missing here?

Upvotes: 1

Views: 183

Answers (1)

user3008107
user3008107

Reputation:

The following code snippet works when executed from activity's onResume method. This is not the best place of course, but it's ok for testing.

    File cacheFile = new File(getFilesDir(), "test.cache");
    List<String> titleArray = new ArrayList<String>(Arrays.asList("a", "b", "c"));

    if (!cacheFile.exists()) {
        try {
            FileWriter out = new FileWriter(cacheFile);
            for (int i = 0; i < titleArray.size(); i++) {
                out.write(titleArray.get(i));
                out.write(System.getProperty("line.separator"));
            }
            out.close();
        } catch (Exception e) {
            Log.e("Test", e.getMessage());
        }
    }

My questions which can lead you to an answer:

  • From what context are you trying to write the file from? BroadcastReceiver? Try from Activity/Service.
  • Are you writing from a background thread or the main one (shouldn't make any imaginable difference)?
  • Are you sure you have enough space? How big is the list? Try writing a very simple file with several bytes and read it back to confirm it worked.
  • Have you tried on different devices and/or the emulator? Does the problem persists?
  • What is the Android version you are building for and testing on?

Upvotes: 1

Related Questions