Write/Read String to/from a File in Android
Introduction
In Android, file handling is crucial for storing and retrieving data persistently. One common task is to save and read strings from/to a file. This article will guide you through the process of writing a string to an internal file and then reading that string back into a String variable.
Writing to a File
To write a string to an internal file:
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()); } }
Reading from a File
To read a string from an internal file:
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; }
Usage
In your code, integrate the writeToFile and readFromFile methods to save the inputted text to the "config.txt" file and retrieve it into the "myID" String variable, respectively.
Conclusion
Using the methods provided in this article, you can easily write and read strings to/from a file in Android, enabling you to persist and retrieve data on the device's internal storage.
The above is the detailed content of How to Write and Read Strings to/from a File in Android?. For more information, please follow other related articles on the PHP Chinese website!