1

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?

5
  • 1
    Try out.flush() before closing the writer. Commented Jun 15, 2014 at 1:20
  • Unfortunately out.flush() did not work. Commented Jun 15, 2014 at 1:24
  • Updated my question to include the cacheFile object. Commented Jun 15, 2014 at 1:27
  • Wait, you were right, I was putting the out.flush() right above the out.close() but after putting the out.flush() within the for loop, it worked. Thanks! Commented Jun 15, 2014 at 1:32
  • 1
    That's strange. It should've worked as out.flush(); out.close(); unless you are getting an exception. Try putting the two into the finally block. Commented Jun 15, 2014 at 1:35

1 Answer 1

1

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?
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.