Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Reading from file (Openfileinput)

Tags:

java

android

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?

like image 799
Will Avatar asked May 17 '11 12:05

Will


2 Answers

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();
like image 102
Spiff Avatar answered Sep 28 '22 20:09

Spiff


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

like image 20
nibuen Avatar answered Sep 28 '22 21:09

nibuen