0

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);
    }
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Jack
  • 271
  • 1
  • 7
  • 15
  • 1
    take look on this thread , will help you to understand the context in android , and feed me back http://stackoverflow.com/questions/3572463/what-is-context-in-android – mohammed momn Feb 17 '14 at 01:51
  • When I tried to get the context via `Context context = this` the `.openFileInput` gives me an error of "The method openFileInput(String) in the type Context is not applicable for the arguments (String, int)" – Jack Feb 17 '14 at 02:02
  • openFileInput this method take only the name of the file you need to open but this method openFileOutput take two arguments file name and the mode – mohammed momn Feb 17 '14 at 02:07

1 Answers1

1

Android Developer site's Documentation about File reading from internal storage says...

To read a file from internal storage:

  1. Call openFileInput() and pass it the name of the file to read. This returns a FileInputStream.
  2. Read bytes from the file with read().
  3. 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);
}
Hamid Shatu
  • 9,664
  • 4
  • 30
  • 41