Topic04_WorkingWithFiles
Topic04_WorkingWithFiles
Overview
⮚ Android devices offer two storage areas, internal and
external.
⮚ The internal storage is private to the application. The user
and other applications cannot access it.
⮚ The external storage is where you store files that will be
shared with other applications or that the user will be able to
access.
2
Overview
⮚ For example, the built-in Camera application stores digital
image files in the external storage so the user can easily
copy them to a computer.
3
Internal Storage
❖ All applications can read from and write to internal storage.
❖ The location of the internal storage is /data/data/[app
package], example so if your application package is
com.example.myapp, the internal directory for this
application is /data/data/com.example.myapp.
4
Internal Storage - Example
❖ Writing data to file.
String filename = “hello.txt”;
String data = “Welcome to our class”;
FileOutputStream fout = openFileOutput(filename, Context.MODE_PRIVATE);
fout.write(data.getBytes());
fout.close();
5
Internal Storage - Example
❖ Reading data from file.
String filename = “hello.txt”;
String data = “”; int c;
FileInputStream fin = openFileInput(filename);
while((c = fin.read()) != -1){
data += Character.toString((char)c));
}
fin.close();
6
Internal Storage
❖ Some functions:
▪ getFileDir(): return the absolute directory path containing the saved files.
▪ getDir(): create or access a directory within the internal storage.
▪ deleteFile(): delete a file stored in the device's internal memory.
▪ fileList(): returns an array of files stored by the current application
instance.
7
External Storage
⮚ There are two types of files that can be written to external
storage, private files and public files.
8
External Storage
⮚ External storage may be removable. As such, there is a
difference between files stored in internal storage and files
stored in external storage as public files.
9
External Storage
⮚ Since external storage can be removed, when you try to
read from or write to it, you should first test if external
storage is available.
10
External Storage
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
return Environment.MEDIA_MOUNTED.equals(state);
} kiem tra
11
External Storage
⮚ The Environment class provides the following fields that you can use
for various file types. cac tap tinh cua external
▪ Directory_ALARMS ▪ Directory_MUSIC
▪ Directory_DCIM ▪ Directory_NOTIFICATIONS
▪ Directory_DOCUMENTS ▪ Directory_PICTURES
▪ Directory_DOWNLOADS ▪ Directory_PODCASTS
▪ Directory_MOVIES ▪ Directory_RINGTONES
12
Demo
Thank you for listening!