Home >Java >javaTutorial >How to Read and Write Strings to an Android File?

How to Read and Write Strings to an Android File?

Barbara Streisand
Barbara StreisandOriginal
2024-12-19 20:01:11322browse

How to Read and Write Strings to an Android File?

Read and Write a String to a File in Android

Overview

In this article, we explore how to store a string in a file on the internal storage of an Android device and subsequently retrieve it for use in your app.

Solution

To begin, you need to save the text from the EditText view to a file. Here's how you can do it:

private void writeToFile(String data, Context context) {
    try {
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("config.txt", Context.MODE_PRIVATE));
        outputStreamWriter.write(data);
        outputStreamWriter.close();
    }
    catch (IOException e) {
        Log.e("Exception", "File write failed: " + e.toString());
    } 
}

Now, you can read the saved file and store its contents in a variable for later use:

private String readFromFile(Context context) {

    String ret = "";

    try {
        InputStream inputStream = context.openFileInput("config.txt");

        if ( inputStream != null ) {
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String receiveString = "";
            StringBuilder stringBuilder = new StringBuilder();

            while ( (receiveString = bufferedReader.readLine()) != null ) {
                stringBuilder.append("\n").append(receiveString);
            }

            inputStream.close();
            ret = stringBuilder.toString();
        }
    }
    catch (FileNotFoundException e) {
        Log.e("login activity", "File not found: " + e.toString());
    } catch (IOException e) {
        Log.e("login activity", "Can not read file: " + e.toString());
    }

    return ret;
}

After implementing these methods, you can invoke writeToFile to save the data to the internal storage and readFromFile to retrieve it.

The above is the detailed content of How to Read and Write Strings to an Android File?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn