Reputation: 271
I 'm reading on how to write to internal storage, and found the following code methods on the Android Developer forum.
In both the the cases, I do not know how to get/invoke the "context"'s method.
I don't understand what the context variable is and how I can create one.
Say I want app read a file on start up.
What is context and how can I use it to achieve reading from storage.
File file = new File(context.getFilesDir(), filename);
FileInputStream fis = context.openFileInput("Data.dat",
Context.MODE_PRIVATE);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader bufferedReader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
Upvotes: 0
Views: 148
Reputation: 9700
Android Developer site's Documentation about File reading from internal storage says...
To read a file from internal storage:
- Call
openFileInput()
and pass it the name of the file to read. This returns aFileInputStream
.- Read bytes from the file with
read()
.- Then close the stream with
close()
.
So, your code to read the file named Data.dat
should be as below.
FileInputStream fis = context.openFileInput("Data.dat");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader bufferedReader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
Upvotes: 1