简体   繁体   中英

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?

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();

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 (eg XML). So i will leave that for you to search on.

Edit: Here is documentation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM