Read/Write a String from/to a File in Android
Reading and writing strings to and from files is a fundamental operation in Android development. This article will demonstrate how to accomplish these tasks using the operating system's built-in file I/O methods.
Writing a String to a File
To save a text string to an internal storage file, follow these steps:
Reading a String from a File
To retrieve the string from the saved file, follow these steps:
Example Code
Here's an example code snippet that demonstrates the aforementioned operations:
Writing:
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:
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; }
The above is the detailed content of How to Read and Write Strings to Files in Android?. For more information, please follow other related articles on the PHP Chinese website!