Will
Will

Reputation: 189

Android: Reading from file (Openfileinput)

I am trying to write a basic "notepad" app for a school project.

I have created the main class with an editText which I save as String textOutput.

I have used the following to save the string to a file:

FileOutputStream fos = openFileOutput(textOutput, Context.MODE_PRIVATE);
fos.write(textOutput.getBytes());
fos.close();

However Android Developers reference says in order to read I should use the following steps:

To read a file from internal storage:

  • Call openFileInput() and pass it the name of the file to read. This returns a FileInputStream.
  • Read bytes from the file with read().
  • Then close the stream with close().

What does this mean, and how do I implement it?

Upvotes: 18

Views: 63760

Answers (2)

Spiff
Spiff

Reputation: 1036

An example of how to use openFileInput:

    FileInputStream in = openFileInput("filename.txt");
    InputStreamReader inputStreamReader = new InputStreamReader(in);
    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
    StringBuilder sb = new StringBuilder();
    String line;
    while ((line = bufferedReader.readLine()) != null) {
        sb.append(line);
    }
    inputStreamReader.close();

Upvotes: 41

nibuen
nibuen

Reputation: 763

The first parameter is the name of the file you are creating/updating when using openFileOutput method. Using the same parameter you have listed above it might look like:

FileInputStream fis = openFileInput(textOutput);

As for reading from a FileInputStream that is extremely well documented here and on the web. The best way to go about it also depends on the type of file you are reading (e.g. XML). So i will leave that for you to search on.

Edit: Here is documentation

Upvotes: 3

Related Questions