"Go" Android essential Knowledge Point-Android files (file) action

Source: Internet
Author: User

Android uses a file system similar to disk-based file systems on other platforms.

This article describes how to use the Android file system to read and write files through the file API.

The File object is suitable for reading or writing large amounts of data in the order from start to finish without skipping. For example, it is suitable for picture files or any content exchanged over the network.

This article shows you how to perform basic file-related tasks in your app.

Assume that you are familiar with the fundamentals of Linux file systems and the standard file input/output APIs in java.io.

Select internal or external storage

All Android devices have two file storage areas: "Internal" and "external" storage. These names were created early in Android, when most devices provided built-in non-volatile memory (internal storage), as well as removable storage media such as micro SD cards (external storage). Some devices divide the persistent storage space into "internal" and "external" partitions, and there is always two storage space, even if there is no Removable storage media, and the API behaves consistently regardless of whether the external storage device is removable. The following list summarizes the actual information about each storage space.

Internal storage:

It is always available.
Only your app can access the files saved here.
When a user uninstalls your app, all of your app's files are removed from the internal storage.
Internal storage is the best choice when you want to make sure that your files are inaccessible to users or other apps.

External storage:

It is not always available because users can mount external storage in the form of a USB storage device and, in some cases, remove it from the device.
It is globally readable, so the files saved here may not be read by you in a controlled manner.
When a user uninstalls your app, the file for your app will be removed from here only when you save your app's files in the directory via Getexternalfilesdir ().
External storage is the best place for files that do not require access restrictions and that you want to share with other apps or allow users to access using a computer.

Note:

Before Android N, internal files can be accessed by relaxing file system permissions for other applications. This is not the case now. If you want other apps to access the contents of your private files, your app can use Fileprovider.

Tips:

Although the app is installed by default in internal storage, you can specify the Android:installlocation attribute in your manifest file so that your app can be installed in external storage. Users prefer this option when the APK is very large and their external storage space is larger than the internal storage. For more information, see where to install your app.

permission to get External storage

To write information to an external store, you must request Write_external_storage permissions in your manifest file.

<manifest ...>
<uses-permission android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/>
...
</manifest>

Note:

Currently, all applications can read external storage without special permissions. However, this will be changed in a future release. If your app needs to read external storage (but not write information to it), then you will need to declare read_external_storage permissions. To ensure that your app continues to work correctly, you should declare this right before the change takes effect.

<manifest ...>
<uses-permission android:name= "Android.permission.READ_EXTERNAL_STORAGE"/>
...
</manifest>

However, if your app uses Write_external_storage permissions, it also implicitly reads the permissions of the external store.
You can save files in internal storage without any permissions. Your app always has permission to read and write in its internal storage directory.

Save the file in internal storage

When you save a file in internal storage, you can get the appropriate directory as file by calling one of the following two methods:

1.getFilesDir ()
Returns a File that represents the internal directory of your app.
2.getCacheDir ()
Returns the file that represents the internal directory of your app's temporary cache file. Be sure to delete any files that you no longer need and implement a reasonable size limit for the amount of memory you use at a specified time, such as 1MB. If the system is about to run out of storage, it will delete your cache files without warning.

to create a new file in one of these directories

1. You can use the file () constructor to pass the file provided by one of the above methods that specify your internal storage directory. For example:

File File = new file (Context.getfilesdir (), filename);
2. Alternatively, you can call Openfileoutput () to get the FileOutputStream of the files written to the internal directory. For example, the following shows how to write some text to a file:

StringFileName= "MyFile";String String = "Hello world!";FileOutputStreamOutputStream;Try {OutputStream=Openfileoutput(FileName, context. Mode_private Outputstream. (string. Getbytes Outputstream.} catch  ( Exception E)  { Eprintstacktrace ();                /span>                

3. Alternatively, if you need to cache some files, you should use Createtempfile () instead. For example, the following method extracts the file name from the URL and is creating the files with that name in your app's internal cache directory:

Public FileGetTempFile(ContextContext, StringUrl) { FileFile; Try { StringFileName= Uri.Parse(Url).Getlastpathsegment();File= file. (filename, null, Context. } catch  (ioexception E)  { //Error while creating File } Span class= "KWD" >return File;               /span>                

Note: Your app's internal storage device directory is specified by your app's package name in a specific location on the Android file system. Technically, if you set the file mode to readable, another app can also read your internal files. However, this app also needs to know the package name and file name of your app. Other apps cannot browse your internal directory and do not have read and write permissions unless you explicitly set the file to be readable or writable. As long as you use mode_private for files on internal storage, other apps will never access them.

Save the file in the external storage

Because external storage may not be available-for example, when a user has mounted the store to a computer or has removed an SD card that provides external storage-you should always confirm its capacity before accessing it. You can query the external storage state by calling Getexternalstoragestate (). If the returned status is media_mounted, you can read and write to your file. For example, the following methods are useful for determining storage availability:

/

* Checks IfExternal storageIsAvailableForReadandWrite*/Public BooleanIsexternalstoragewritable() { String State = environment.< Span class= "PLN" >getexternalstoragestate (); if  (environment.media_mounted. (state { return true;} return false}             /span>                
/* Checks If external storage is available to at least read */Public BooleanIsexternalstoragereadable() { StringState= Environment.Getexternalstoragestate(); If (environment.. Equals (state)  | |  environment. Media_mounted_read_only. Equals (state { return true;} return false}             /span>                 
Although external storage can be modified by users and other applications, you can save two types of files here: Public Files

Files that should be freely available to other applications and users. Users should still be able to use these files when they uninstall your app.
For example, your app takes a photo or other downloaded file.

Private File

Files that belong to your app and should be deleted when the user uninstalls your app. Although these files are technically accessible to users and other applications (because they are stored in external storage), they do not actually provide any output value to users outside your app. When a user uninstalls your app, all files in the app's external private directory are deleted.
For example, your app downloads additional resources or temporary media files.

If you want to save the public file on an external storage device, use the Getexternalstoragepublicdirectory () method to get the file that represents the appropriate directory on the external storage device. The method uses parameters that specify the types of files that you want to save so that they can be logically organized with other public files, such as Directory_music or directory_pictures. 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;
}
If you want to save your app-specific files, you can get the appropriate directory by calling Getexternalfilesdir () and passing it a name indicating the type of directory you want. Each directory created by this method is added to the parent directory of all external storage files that encapsulate your app, and the files are deleted when the user uninstalls your app.

For example, you can use the following methods to create a catalog of personal albums:

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

If there is no intended subdirectory name for your file, you can call Getexternalfilesdir () instead and pass null. This will return the root directory of your app's private directory on the external store.

Remember that Getexternalfilesdir () creates directories in directories that are deleted when the user uninstalls your app. If the file you are saving should still be available after the user uninstalls your app-for example, when your app is a camera and the user wants to keep the photo-you should use Getexternalstoragepublicdirectory () instead.

Whether you use {@linkandroid for shared files. Os.environment#getexternalstoragepublicdirectory getexternalstoragepublicdirectory ()} It is also important that you use Getexternalfilesdir () for your application-specific files, and that you use the directory names provided by API constants such as Directory_pictures. These directory names ensure that the files are handled correctly by the system. For example, files saved in Directory_ringtones are categorized by the system media scanner as ringtones, not music.

Querying available space

If you know in advance the amount of data you will save, you can find out if there is enough free space without calling Getfreespace () or gettotalspace () to cause ioexception. These methods provide the current free space and the total space in the storage volume, respectively. This information can also be used to avoid populating a storage volume so that it exceeds a specific threshold value.

However, the system does not guarantee that you can write as many bytes as indicated by Getfreespace (). If the returned number is a few megabytes larger than the size of the data you want to save, or if the file system occupies less than 90% of the space, you can safely continue the operation. Otherwise, you might not be writing to the store.

Note: You do not need to check the amount of free space before saving your files. You can try to write the file immediately and then capture it when the IOException appears. If you do not know the exact amount of space you need, you may need to do so. For example, if you change the encoding of a file by converting the PNG image to JPEG before saving the file, you will not know the size of the file beforehand.

Deleting Files

You should always delete files that you no longer need. The most straightforward way to delete a file is to have the open file reference call Delete () yourself.

Myfile.delete ();
If the file is saved in the internal store, you can also request that the Context locate and delete the file by calling DeleteFile ():

Mycontext.deletefile (FileName);

Note: When a user uninstalls your app, the Android system deletes the following:

All files that you save in the internal store
You use Getexternalfilesdir () to save all the files in the external storage.
However, you should manually delete all cached files that were created periodically using getcachedir () and periodically delete other files that you no longer need.

"Go" Android essential Knowledge Point-Android files (file) action

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.