3

So far I have made a text file in my assets folder and I can read it fine and does what it is supposed to do. When I write to it using the following:

 FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE); 
 fos.write(("0").getBytes());
 fos.close()

it works. However when I close my app and reopen it later, it does not remember anything I changed it to.

Any ideas?

BryanH
  • 5,826
  • 3
  • 34
  • 47
alex wilhelm
  • 233
  • 5
  • 16

2 Answers2

0

Files in assets or raw are intended to be read-only, so copy it to a new location (like in Environment.getDataDirectory()) and then you should be able to write to it.


I would think this would throw some type of exception do you have an empty catch block? At a minimum you should use e.printStackTrack() otherwise your app will silently fail...

try {
    FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE); 
    fos.write(("0").getBytes());
    fos.close();
} catch (Exception e) {
    e.printStackTrace();
}
Sam
  • 86,580
  • 20
  • 181
  • 179
  • Thanks, but where would I move it to? – alex wilhelm Dec 19 '12 at 00:34
  • You have a number of choices, like `getFilesDir()` or `getDir()` in the "Other Useful Methods" subsection of [Data Storage](http://developer.android.com/guide/topics/data/data-storage.html#filesInternal). – Sam Dec 19 '12 at 00:45
  • Thanks again, but now i have no clue on how to put it into the Environment.getDataDirectory()... If you could give me an example that would be great... I just did a quick google search and couldn't find what i was looking for... Thanks again so far you have helped me a lot!! – alex wilhelm Dec 19 '12 at 00:48
  • I found this answer: [Android: How to copy files in 'assets' to sdcard?](http://stackoverflow.com/a/11212942/1267661). Let me know if it helps. – Sam Dec 19 '12 at 00:54
  • Thanks so much I am going to try that now – alex wilhelm Dec 19 '12 at 00:58
0

I think you just forget to call flush after writting

FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE); 
 fos.write(("0").getBytes());
 fos.flush();
 fos.close();
Festus Tamakloe
  • 11,231
  • 9
  • 53
  • 65