java-meiomidpseries-40

reading from/writing to a file in J2ME without continually pestering the user


I'm writing a simple J2ME phone app and I want to save the status of the app when I exit it.
Googling around led me to the FileConnection class:

FileConnection filecon = (FileConnection) Connector.open("file:///E:/mynewfile.txt");
filecon.create();
// write data to file etc etc

and such like. This all seems to work, but it has the following two drawbacks. On my S40 phone, every time I run the app, I am asked "let application (blah) write to a file?" or some such thing. I have other apps that can save their states (e.g. games that save a high score table) and which don't ask me every time about whether they can write to a file. What is the trick I'm missing?

And while I'm here -- the "///E:/mynewfile.txt" file name isn't ideal either, because it works for my phone but doesn't work for my son's phone (and why should it?), meaning I have to edit and recompile the app every time I want the program to run on a new phone (I can envisage some sort of kludge where the program establishes whose phone the app is running on -- there will just be a few of us using it -- and then sets a string pointing to a valid file in a valid directory accordingly, but this is surely not how it's supposed to be done...). Presumably I shouldn't be writing to E:/ anyway, but is there some sort of canonical "place where application X puts all its data files"? And is it somehow device-independent, at least to some extent? Again, presumably I'm missing a trick -- and the two issues I'm asking about are perhaps related.

What should I be doing?


Solution

  • My own answer to my question: I can use the methods of the RecordStore class to read and write to a file which is placed in the resources of the program.