Android file storage

Source: Internet
Author: User


For Android to use the file system to read and save the file, refer to the java.io package below for the relevant package.

1) Select internal Storage (Internal Storage) or external storage (External Storage)

Android device has two storage areas: internal storage and external storage space, as the name implies, internal storage is following the Android system, external systems are removable devices such as SD card.
For many Android devices, even without the previously mentioned external devices (such as SD card), the system also provides a piece of space on the internal storage area as "external storage". So even if
There are no removable peripherals, and the latter two sets of storage space are still available for selection. The API is equally applicable to both external devices. Here are some of the features of the two storage spaces:
A. Internal equipment (Internal Storage)
1. Internal equipment is always in existence and is always valid.
2. By default, files stored on an internal device can only be accessed individually by their own app.
3. When the app is uninstalled, all app files saved on the internal device will be removed.
As you can see from the above, internal devices are suitable for storing data and files accessed only by their own apps. such as user information after login, database files and other private information.
B. External equipment (External Storage)
1. External equipment is not guaranteed to be present and valid. For example, user may mount an external device and remove it.
2. External devices are "public areas", files stored on external devices cannot control their privacy, and other apps can read and manipulate it.
3. When the app is uninstalled, only the files stored in the Getexternalfilesdir () folder will be removed, and the other files will not be removed voluntarily. In other words, garbage data is generated.
Comparing the internal devices, you can see that the external device is suitable for storing files that do not require Read permissions.
2) Get read and Write permissions.
To read external devices, you need to add read and write permissions to the manifest:
<manifest ...>
<uses-permission android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/>
...
</manifest>
It is important to note that all apps now have the ability to read external devices without the need for special Read permissions. However, in future versions of Android, more restrictions will be added.
So in your app, it's also necessary to add Read permissions to prevent future updates from being brought into trouble.
<manifest ...>
<uses-permission android:name= "Android.permission.READ_EXTERNAL_STORAGE"/>
...
</manifest>

No permissions are required to read and write internal devices. The app has the right to read and write to its internal storage space.
3) store files to internal devices
When you need to store files into the internal space, you can get the storage path through two methods of the file class
Getfilesdir () will return the path to your app's internal storage space
Getcachedir () returns the cache directory of your app's internal storage, and if the cache file is not needed, clean up the guaranteed cache directory to ensure that the cache file does not take up too much space.
such as 1M, or the system may be without warning directly delete files in the cache directory.

If you want to create a file on your back device, you can use the following code:
File File = new file (Context.getfilesdir (), filename);

Accordingly, you can use Openfileoutput () to get the FileOutputStream and then write the file to the internal device through it. Here is an example:

String filename = "myfile";  String string = "Hello world!";  FileOutputStream OutputStream;  try {    outputstream = openfileoutput (filename, context.mode_private);    Outputstream.write (String.getbytes ());    Outputstream.close ();  } catch (Exception e) {    e.printstacktrace ();  }  


Or, you can also use Createtempfile () to create a file, the following example is the URL to get the file name, and then saved in the cache directory:
Public file GetTempFile (context context, String URL) {    file file;    try {        String fileName = uri.parse (URL). getlastpathsegment ();        File = File.createtempfile (FileName, NULL, Context.getcachedir ());    catch (IOException e) {        //Error while creating file    }    return file;  }



The internal device directory is stored in your package name, technically, if you save the file in readble mode, the other app can read the file, and of course it needs to know
Your package name and your file name. Other apps can't browse your internal folders, if you don't have the file attributes set to readable or writable.
As long as you use Mode_private mode, other apps won't be able to access your files.

4) External storage space
Because the external space is removable, you must ensure that it exists before you access it. Android provides a responsive interface to determine if the peripherals are available. When the status of the peripheral is media_mounted, it means that the peripheral can read and write.
The following code can be used to check if the peripherals are available
/* Checks If external storage is available for read and write *  /public boolean isexternalstoragewritable () {    stri ng state = Environment.getexternalstoragestate ();    if (Environment.MEDIA_MOUNTED.equals (state)) {        return true;    }    return false;  }  /* Checks If external storage is available to at least Read *  /public boolean isexternalstoragereadable () {    String State = Environment.getexternalstoragestate ();    if (Environment.MEDIA_MOUNTED.equals (state) | |        Environment.MEDIA_MOUNTED_READ_ONLY.equals (state)) {        return true;    }    return false;  }



As mentioned before, the files on the peripherals are also different, and some of the apps will be deleted as the app is uninstalled, and some of the files will not be deleted at the same time.
Therefore, depending on the type of file you have, you can choose to save them in a different directory:
Common documents:
These files can be used by other apps at the same time, when uninstalled, do not want to be deleted, such as downloading pictures, or using the app to take photos and so on.
Private files:
Your app's standalone files, when uninstalled, want to be deleted at the same time, although these files can be accessed by other apps, they are no longer valuable to the user. For example, some cache data.

When you save a common file, you can use the Getexternalstoragepublicdirectory () method to get the root of the peripheral and create a new file path on the root directory.
This method needs to specify the type of storage you need, such as slices or music. For example:

  Public File Getalbumstoragedir (String albumname) {    //Get The directory for the user ' s public pictures directory.     File File = new file (environment.getexternalstoragepublicdirectory (            environment.directory_pictures), AlbumName) ;    if (!file.mkdirs ()) {        log.e (Log_tag, "Directory not created");    }    return file;  }



When you need to store a private file, you can also specify the desired type by Getexternalfilesdir (), as in the following example:

Public File Getalbumstoragedir (context context, String Albumname) {    //Get the directory for the app's private picture S directory.     File File = new file (Context.getexternalfilesdir (            environment.directory_pictures), albumname);    if (!file.mkdirs ()) {        log.e (Log_tag, "Directory not created");    }    return file;  }



If you do not need to specify a type, you can pass NULL to Getexternalfilesdir (), which returns the root directory of your application that is stored externally.

Remember the difference between the two.

5) Query the remaining space
If you know the size of the files you need to save, you need to make sure you have enough space to store the files.
The size of the file can be obtained by getfreespace () or Gettotalspace ().

6) Delete files:
You can delete files by using the Delete () method of file. Or, you can delete the internal space file by using Context.detelefile (FileName).





































Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android file storage

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.