Presentation is loading. Please wait.

Presentation is loading. Please wait.

Data Storage: Part 2 (File System)

Similar presentations


Presentation on theme: "Data Storage: Part 2 (File System)"— Presentation transcript:

1 Data Storage: Part 2 (File System)

2 Internal and External Storage
Android devices have two file storage areas commonly referred to as “internal” and “external” storage. Many Android devices offer built-in non-volatile memory (internal storage) plus a removable storage medium such as a micro SD card (external storage). Some devices divide the permanent storage space into “internal” and “external” partitions, so even without a removable storage medium, there are always two storage spaces, and the API behavior is the same whether or not external storage is removable. ©SoftMoore Consulting

3 Internal and External Storage
Internal storage − for private data Always available. By default, files saved to the internal storage are private to your application, and other applications cannot access them. When the user uninstalls an application, files and directories created by that application in internal storage are removed. External storage − for public shared data Not always available (can be a removable storage media). Files saved to the external storage are world-readable and can be modified by the user or other applications. When the user uninstalls an application, files and directories created in external storage are not removed unless they are saved in the directory from getExternalFilesDir(). ©SoftMoore Consulting

4 Using Java I/O for Data Storage
The standard Java I/O capabilities provided in package java.io can be used to read and write data files on an Android device’s internal and external storage. Android provides several helper methods inherited from android.content.Context that can be used access files on the device. Application files are saved in the folder /data/data/<package name>/files ©SoftMoore Consulting

5 Using Android Device Monitor to Explore an Emulator’s File System
Android Device monitor can be used to explore a device’s file system and to transfer files between a computer and an Android device. In Android Studio, go to Tools → Android → Android Device Monitor make sure the DDMS button at the top is clicked Select a device and click on the File Explorer tab. Note 1: Access to the internal storage of a “real” device is restricted. Note 2: Android Device Monitor fails to show files for Android 24 and 25 emulators. This is a known bug and has been reported to Google. See ©SoftMoore Consulting

6 Using adb Command Line to Explore an Emulator’s File System
Preparation add environment variables ANDROID_SDK_HOME; e.g., C:\Users\jdoe\AppData\Local\Android\sdk ANDROID_AVD_HOME; e.g., C:\Users\jdoe\.android\avd add the following to your PATH environment variable: %ANDROID_AVD_HOME% %ANDROID_SDK_HOME% %ANDROID_SDK_HOME%\tools %ANDROID_SDK_HOME%\platform-tools Start a virtual device (emulator) and launch the ADB shell to connect to the database from a command prompt. Put this one first – above the others. (see example on next slide) ©SoftMoore Consulting

7 Example: Using adb Command Line to Explore an Emulator’s File System
C:\JMoore>adb devices List of devices attached emulator-5554 device C:\JMoore>adb -s emulator-5554 shell generic_x86:/ $ su generic_x86:/ # ls -l total 3688 drwxr-xr-x 27 root root :53 acct lrwxrwxrwx 1 root root :00 bugreports ->... drwxrwx--- 6 system cache :46 cache lrwxrwxrwx 1 root root :00 charger -> ... drwxr-xr-x 3 root root :53 config lrwxrwxrwx 1 root root :00 d -> ... drwxrwxrwx 36 system system :50 data -rw-r--r-- 1 root root :00 default.prop drwxr-xr-x 14 root root :53 dev ... ©SoftMoore Consulting

8 Helper Methods Inherited From android.content.Context
FileInputStream openFileInput(String name) Open a private file for reading. FileOutputStream openFileOutput(String name, int mode) Open a private file for writing or appending. File getFilesDir() Get the absolute path to the file system directory where internal files are saved Returns a File object for /data/data/<package name>/files/. File getDir(String name, int mode) Create (or open an existing) directory within your internal storage space. ©SoftMoore Consulting

9 Helper Methods Inherited From android.content.Context (continued)
boolean deleteFile(String name) Delete the given private file associated with this application. Returns true if the file was successfully deleted; otherwise returns false. String[] fileList() Returns an array of strings naming the private files associated with this application. File getExternalFilesDir(String type) Get the absolute path to the directory on the primary shared/external storage device where the application can place files that it owns. Starting in KitKat (API level 19), no permissions are required by the application to read or write to the returned path. No security is enforced for these files – other applications with WRITE_EXTERNAL_STORAGE permission can access these files. ©SoftMoore Consulting

10 File Modes Selected file modes from android.content.Context
MODE_APPEND If the file already exists, then write data to the end of the existing file instead of erasing it. MODE_PRIVATE Created file can only be accessed by the calling application (default mode). MODE_WORLD_READABLE (deprecated in API level 17) Allow all other applications read access to the created file. MODE_WORLD_WRITEABLE (deprecated in API level 17) Allow all other applications write access to the created file. ©SoftMoore Consulting

11 Example: Reading from a Text File
BufferedReader br = null; try { FileInputStream fis = openFileInput(FILE_NAME); br = new BufferedReader(new InputStreamReader(fis)); StringBuilder builder = new StringBuilder(200); String line = null; while((line = br.readLine()) != null) builder.append(line + '\n'); EditText editText = (EditText) findViewById(R.id.editText); editText.setText(builder.toString()); } (continued on next slide) ©SoftMoore Consulting

12 Example: Reading from a Text File (continued)
catch (FileNotFoundException ex) { String errorMsg = FILE_NAME + " not found"; Log.e(LOG_TAG, errorMsg, ex); Toast toast = Toast.makeText(FileStorage.this, errorMsg, Toast.LENGTH_SHORT); toast.show(); } catch (IOException ex) ... // log and report error message finally ... // if br != null, try to call br.close() // log and report error message ©SoftMoore Consulting

13 Example: Writing to a Text File
BufferedWriter bw = null; try { FileOutputStream fos = openFileOutput(FILE_NAME, MODE_PRIVATE); bw = new BufferedWriter(new OutputStreamWriter(fos)); EditText editText = (EditText) findViewById(R.id.editText); String text = editText.getText().toString(); bw.write(text, 0, text.length()); } (continued on next slide) ©SoftMoore Consulting

14 Example: Writing to a Text File (continued)
catch (FileNotFoundException ex) { String errorMsg = FILE_NAME + " not found"; Log.e(LOG_TAG, errorMsg, ex); Toast toast = Toast.makeText(FileStorage.this, errorMsg, Toast.LENGTH_SHORT); toast.show(); } catch (IOException ex) ... // log and report error message finally ... // if bw != null, try to call bw.close() // log and report error message ©SoftMoore Consulting

15 File Storage Example ©SoftMoore Consulting

16 External Storage In order to read or write files on the external storage, an application must acquire system permissions READ_EXTERNAL_STORAGE or WRITE_EXTERNAL_STORAGE. Both are considered dangerous – must be checked at runtime. Permission WRITE_EXTERNAL_STORAGE implicitly requires read assess – you don’t need to request both. Example <manifest ...> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> ... </manifest> ©SoftMoore Consulting

17 Checking Media Availability for External Storage
There is no security enforced upon files you save to the external storage. All applications with appropriate permissions can read and write files placed on the external storage and the user can remove them. Call getExternalStorageState() before using external storage to check whether the media is available. The media could be mounted on the device, missing, read-only, or in some other state. ©SoftMoore Consulting

18 Example: Checking Media Availability
boolean isExternalStorageAvailable = false; boolean isExternalStorageWriteable = false; String state = Environment.getExternalStorageState(); if (state.equals(Environment.MEDIA_MOUNTED)) { // We can both read and write. isExternalStorageAvailable = true; isExternalStorageWriteable = true; } else if (state.equals(Environment.MEDIA_MOUNTED_READ_ONLY) { // We can only read. isExternalStorageAvailable = true; isExternalStorageWriteable = false; } else (continued on next slide) ©SoftMoore Consulting

19 Example: Checking Media Availability (continued)
{ // We can neither read nor write. isExternalStorageAvailable = false; isExternalStorageWriteable = false; } ©SoftMoore Consulting

20 Public Directories on External Storage
Files saved in one of the public share directories on external storage are not deleted when an application is uninstalled. Examples include the following Music/ – media scanner classifies all media found here as user music Ringtones/ – media scanner classifies all media found here as a ringtone Alarms/ – media scanner classifies all media found here as an alarm sound Pictures/ – all photos (excluding those taken with the camera) Movies/ – all movies (excluding those taken with the camcorder) ©SoftMoore Consulting

21 Accessing Files on External Storage
To access application-independent files on external storage, use one of these static methods in class android.os.Environment. File getExternalStorageDirectory() File getExternalStoragePublicDirectory() To access application-specific files on external storage, use this method in class android.content.Context. File getExternalFilesDir() Details of these methods are provided on next couple of slides. ©SoftMoore Consulting

22 Accessing Application-Independent Files on External Storage
File getExternalStorageDirectory() Returns the primary shared/external storage directory (i.e., the top-level directory in external storage). File getExternalStoragePublicDirectory(String type) Returns a top-level shared/external storage directory for placing files of a particular type. Parameter specifies the type of storage directory to return. DIRECTORY_MUSIC DIRECTORY_PICTURES DIRECTORY_RINGTONES ... // may not be null Files are stored in these directories are not deleted when the application is uninstalled. ©SoftMoore Consulting

23 Accessing Application-Specific Files on External Storage
File getExternalFilesDir(String type) Get the absolute path to the directory on the primary shared/external storage device where the application can place files that it owns. Starting in KitKat (API level 19), no permissions are required by the application to read or write to the returned directory. Files are stored in /sdcard/Android/data/<package name>/ Files are deleted when the application is uninstalled. No security is enforced for these files – other applications with WRITE_EXTERNAL_STORAGE permission can access these files. Parameter specifies the type of subdirectory. DIRECTORY_MUSIC DIRECTORY_RINGTONES ... null to get the root of your application’s file directory (i.e., /sdcard/Android/data/<package name>/files) ©SoftMoore Consulting

24 Relevant Links Data Storage Class Context
Class Context The Java Tutorials: Basic I/O ©SoftMoore Consulting


Download ppt "Data Storage: Part 2 (File System)"

Similar presentations


Ads by Google