Read/Write String from/to a File in Android

To read and write a string from and to a file in Android, you can use the FileInputStream and FileOutputStream classes along with the InputStreamReader and OutputStreamWriter classes.

Here is an example of how to write a string to a file:

String text = "Hello, World!";
File file = new File(getFilesDir(), "hello.txt");

FileOutputStream fos = new FileOutputStream(file);
OutputStreamWriter osw = new OutputStreamWriter(fos);
osw.write(text);
osw.flush();
osw.close();
fos.close();

This will write the string "Hello, World!" to the file "hello.txt" in the internal storage of the app.

To read the string from the file, you can use the following code:

File file = new File(getFilesDir(), "hello.txt");

FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);

StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
    sb.append(line);
}

String text = sb.toString();

br.close();
isr.close();
fis.close();

This will read the contents of the file "hello.txt" line by line and append them to a string builder, and then convert the string builder to a string.

Keep in mind that you will need to add the READ_EXTERNAL_STORAGE and WRITE_EXTERNAL_STORAGE permissions to your app's manifest file if you want to read and write files to the external storage (SD card) of the device.

For example:

<manifest>
    <!-- other manifest elements -->
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</manifest>

You will also need to request these permissions at runtime if your app is targeting Android 6.0