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.
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");
try (FileOutputStream fos = new FileOutputStream(file);
OutputStreamWriter osw = new OutputStreamWriter(fos, StandardCharsets.UTF_8)) {
osw.write(text);
}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");
StringBuilder sb = new StringBuilder();
try (FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis, StandardCharsets.UTF_8);
BufferedReader br = new BufferedReader(isr)) {
String line;
while ((line = br.readLine()) != null) {
sb.append(line).append('\n');
}
}
String text = sb.toString();This will read the contents of the file "hello.txt" line by line, preserving newlines, and then convert the string builder to a string.
Note that the example above uses internal storage (getFilesDir()), which does not require any permissions. If you want to read and write files to external storage, you will need to add the READ_EXTERNAL_STORAGE and WRITE_EXTERNAL_STORAGE permissions to your app's manifest file:
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.