Android offers three main storage options: Internal Storage, External Storage, and Shared Preferences.
1. Internal Storage: Private to the app, used for storing sensitive data or files that don’t require user access. Ideal for caching data, temporary files, or app-specific settings.
Example:
FileOutputStream fos = openFileOutput("example.txt", Context.MODE_PRIVATE);
fos.write(data.getBytes());
fos.close();
2. External Storage: Accessible by both the app and users, suitable for non-sensitive data or files shared with other apps. Use when needing to store large files, media, or documents.
Example:
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), "example.txt");
FileOutputStream fos = new FileOutputStream(file);
fos.write(data.getBytes());
fos.close();
3. Shared Preferences: Key-value pairs for small amounts of primitive data types, ideal for saving simple app configurations or user preferences.
Example:
SharedPreferences sharedPreferences = getSharedPreferences("MyPrefs", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("username", "JohnDoe");
editor.apply();