Reputation: 81
I've been fooling around with the android platform, messing around with different ways of storing data. Right now I am using the Context
methods openFileInput()
and openFileOutput()
.
I created a file called default just as the documentation for these two methods told me. Here's some example code (these examples are replicas of what I did, I am aware that the filename and variables are named differently):
openFileOutput()...
Context cont = /* defined somewhere */;
String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos = cont.openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.flush();
fos.close();
openFileInput()...
FileInputStream fis = cont.openFileInput("hello_file");
byte[] buffer = new byte[(int) fis.getChannel().size()];
fis.read(buffer);
String str= "";
for(byte b:buffer) str+=(char)b;
fis.close();
In these code snippets, "hello world" should be written to the file "hello_file", and should be what's in str
. The problem I'm having with my code is that no matter what I write to my file, the FileInputReader
picks up nothing.
I scrolled through the permissions listed in the android documentation, but I could not find anything about internal storage (and I am pretty sure you don't need a permission for something like this).
The bottom line is, I don't understand why the FileInputWriter
isn't writing anything or why the FileInputReader
isn't reading anything (I don't know which it is) when the code runs fine and without error.
Upvotes: 2
Views: 5261
Reputation: 11892
I write back as answer, because this is getting too much for a comment. I've tried your code - and well, it just works fine.
The only thing I can imagine is, that your device has a problem. In which case I would expect some exception...
What you still can do, is to copy my code and check the log. See if it works, or if you might get some exception. Then check how much internal memory you got in your device (is it real or emulated?)
If it is emulated it might be too small for even such a small file.
Here's my code, that I put into onResume()
String FILENAME = "hello_file";
String string = "hello world!";
try {
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.flush();
fos.close();
} catch (IOException e) {
Log.e("STACKOVERFLOW", e.getMessage(), e);
}
try {
FileInputStream fis = openFileInput("hello_file");
byte[] buffer = new byte[(int) fis.getChannel().size()];
fis.read(buffer);
String str= "";
for(byte b:buffer) str+=(char)b;
fis.close();
Log.i("STACKOVERFLOW", String.format("GOT: [%s]", str));
} catch (IOException e) {
Log.e("STACKOVERFLOW", e.getMessage(), e);
}
The output:
08-16 08:31:38.748: I/STACKOVERFLOW(915): GOT: [hello world!]
Is there a category of: "Helpful, but not sovling the problem"?
Upvotes: 1