External storage refers to the storage media that can be physically removed from the device, such as SD cards. It's useful for storing large files or data that needs to be shared with other apps or devices.
Accessing External Storage:
Before accessing external storage, you need to check if it's available and request necessary permissions from the user.
Java
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_WRITE_EXTERNAL_STORAGE_PERMISSION);
} else {
// Access external storage
}
Writing to External Storage:
Java
File externalStorageDir = Environment.getExternalStorageDirectory();
File file = new File(externalStorageDir, "myFile.txt");
FileOutputStream fos = new FileOutputStream(file);
fos.write("Hello, world!".getBytes());
fos.close();
Reading from External Storage:
Java
File file = new File(Environment.getExternalStorageDirectory(), "myFile.txt"); FileInputStream fis = new FileInputStream(file); byte[] buffer = new byte[1024]; int bytesRead; StringBuilder sb = new StringBuilder(); while ((bytesRead = fis.read(buffer)) != -1) { sb.append(new String(buffer, 0, bytesRead)); } fis.close(); String fileContent = sb.toString();
Key Points to Remember:
Permissions: Always request necessary permissions from the user before accessing external storage.
Storage State: Check the state of the external storage using Environment.getExternalStorageState() to ensure it's available and writable.
File Paths: Use Environment.getExternalStorageDirectory() to get the root directory of the external storage.
Error Handling: Handle potential exceptions like IOException to ensure robust file operations.
User Experience: Provide clear instructions to the user about the storage permissions and the purpose of accessing external storage.
Additional Considerations:
Public Storage: Data stored in public directories on external storage can be accessed by other apps.
Private Storage: You can create private directories within your app's specific directory on external storage.
Media Storage: Use the MediaStore API to access and manage media files like images, audio, and video.
By following these guidelines, you can effectively use external storage to store and retrieve data in your Android app, providing a seamless user experience.