Data Persistence
Files (Internal Storage)
Android Internal Storage
● Data files are stored locally on the device’s internal memory using a
FileOutputStream object.
● We can read the data files from the device using a FileInputStream object.
● To read & write Data files, they can be accessed from any context within the app.
● Data files are secured as they can’t be accessed from outside of the app.
● The Data files are automatically deleted on uninstalling the app.
2
Android Internal Storage
Write a File to Internal Storage
● We can easily generate and write data to a file in the internal storage by using the
android FileOutputStream object openFileOutput method.
3
Android Internal Storage
Write a File to Internal Storage
String FILENAME = "demo_details";
String name = "admin";
FileOutputStream fstream = openFileOutput(FILENAME,
Context.MODE_PRIVATE);
fstream.write(name.getBytes());
fstream.close();
4
Android Internal Storage
We have different modes:
- MODE_APPEND
- MODE_WORLD_READBLE
- MODE_WORLD_WRITEABLE
5
Android Internal Storage
We have different methods (Write):
getChannel()
- It returns the unique FileChannel object associated with this file output stream.
getFD()
- It returns the file descriptor which is associated with the stream.
write(byte[] b, int off, int len)
- It writes len bytes from the specified byte array starting at offset off to the file
output stream.
6
Android Internal Storage
Read a File from Internal Storage
● We read data from a file in the internal storage by using the android
FileInputStream object openFileInput method.
7
Android Internal Storage
Read a File from Internal Storage
String FILENAME = "demo_details";
FileInputStream fstream = openFileInput(FILENAME);
StringBuffer sbuffer = new StringBuffer();
int i;
while ((i = fstream.read())!= -1){
sbuffer.append((char)i);
fstream.close();
8
Android Internal Storage
We have different methods (Read):
getChannel()
- It returns the unique FileChannel object associated with this file output stream.
getFD()
- It returns the file descriptor which is associated with the stream.
write(byte[] b, int off, int len)
- It reads len bytes of data from the specified file input stream into an array of bytes.
9
Internal Storage Example (Code)
Activity_main.xml
AndroidManifest.xml
Details.xml
DetailsActivity.java
MainActivity.java
10