Persisting Data to Files in Android
1. Saving to Internal Storage
Internal storage is private to the application and cannot be accessed by other apps.
Files stored here are deleted when the app is uninstalled.
String filename = "myfile.txt";
String fileContents = "Hello, Android!";
try (FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(fileContents.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
try (FileInputStream fis = openFileInput("myfile.txt");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr)) {
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
String fileContents = sb.toString();
} catch (IOException e) {
e.printStackTrace();
}
2. Saving to External Storage
External storage is accessible to other apps and users.
It requires proper permissions in AndroidManifest.xml.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File file = new File(getExternalFilesDir(null), "myfile.txt");
try (FileOutputStream fos = new FileOutputStream(file)) {
fos.write("Hello, External Storage!".getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
File file = new File(getExternalFilesDir(null), "myfile.txt");
try (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).append("\n");
}
String fileContents = sb.toString();
} catch (IOException e) {
e.printStackTrace();
}
Conclusion
Android allows data persistence using internal and external storage.
Internal storage is private to the app, while external storage is accessible to other apps.
Permissions are required for external storage access.