Internal storage is a secure and private way to store data specific to your Android app. This data is not accessible to other apps on the device, ensuring its confidentiality.
How to Use Internal Storage:
Obtain a File Output Stream:
Java
FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE);
openFileOutput() takes two arguments:
Filename: The name of the file to be created.
Mode: Context.MODE_PRIVATE ensures that only your app can access the file.
2. Write Data to the File:
Java
fos.write(data.getBytes());
fos.close();
Use fos.write() to write data to the file.
Remember to close the FileOutputStream to release resources.
3. Read Data from the File:
Java
FileInputStream fis = openFileInput(filename);
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();
Use openFileInput() to open the file for reading.
Read data from the file using a byte array and a loop.
Close the FileInputStream to release resources.
Example: Saving and Reading a Text File
Java
// Save a text file
String textToSave = "Hello, world!";
FileOutputStream fos = openFileOutput("myFile.txt", Context.MODE_PRIVATE);
fos.write(textToSave.getBytes());
fos.close();
// Read the text file
FileInputStream fis = openFileInput("myFile.txt");
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:
Internal storage is ideal for storing small to medium-sized files that are specific to your app.
Data stored in internal storage is deleted when the app is uninstalled.
For larger files or data that needs to be accessible to other apps, consider using external storage.
Always handle file operations in a try-catch block to catch potential exceptions.
By following these guidelines, you can effectively use internal storage to store and retrieve data in your Android app.