Android File Save

Select internal or external storage

All Android device has two file storage area: the "internal" and "external" memory. Early, most of these names from the device provides Android built a nonvolatile memory (internal memory), and a removable storage medium, such as a microSD card (external memory). Now, many devices permanently into separate memory space "internal" and "external" partition. Therefore, even without the removable storage media, both storage space is always present, whether or not removable external storage, API behavior is the same.

Since the external memory may be removable, so there are some differences between these two options, as shown below.
Internal memory:

    It is always available.
    Files saved in the internal memory can only be accessed by your application.
    When users uninstall your application, the system will delete all the files from the application of internal storage.
    When you want to ensure that users and other applications can not access your files, it is best to use internal storage.

External memory:

    The external storage is not always available, because users can be mounted as an external USB memory store, and removed from the apparatus in some cases.
    External storage is world-readable, so here is saved in a file might read outside of your control.
    When users uninstall your application, only files stored in the application's directory acquired by using getExternalFilesDir (), the system will delete the file for the application from here.
    For file access restrictions and you do not need to share files with other applications or allow users to use the computer to access the external storage is the best location.

Save the file in the internal memory

Internal storage directory of your application package by the name of your application specifies a special place in Android file system, you can use the following API access.

    Note: external storage directories different, your application does not require any system privileges to read and write internal directory returned by these methods.

Write a file

When you save a file to the internal storage, you can get the appropriate directory by calling the following two methods, further action File:

    getFilesDir (): Returns the File that the application of internal directory.
    getCacheDir (): Returns the File temporary cache files that the application of internal directory.

To create a new directory in which a file can be used File () constructor, passing inside the specified method to the File storage directory provided by the above-described method.

E.g:

    File file = new File(context.getFilesDir(), filename);
     

Or, you can call openFileOutput () to get the contents of the file FileOutputStream written internal directory.

For example, here's how to write some text file:

    String filename = "myfile";
    String fileContents = "Hello world!";
    FileOutputStream outputStream;
     
    the try {the outputStream = openFileOutput (filename, Context.MODE_PRIVATE); OutputStream.write (fileContents.getBytes ()); outputStream.close ();} the catch (Exception E) {e.printStackTrace ();} MODE_PRIVATE file will be created ( file or replace with the same name), and private file as its application. Other available modes include: MODE_APPEND, MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE. Please note that this openFileOutput () method requires file mode parameters. Transfer MODE_PRIVATE will create a file (or replace the file with the same name), and set it as a private file applications. Other available modes include: MODE_APPEND, MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE. Since the API level 17, and the constants MODE_WORLD_READABLE MODE_WORLD_WRITEABLE has been deprecated. Starting Android N (7.0, API24), use these constants would lead to trigger SecurityException. This means, for Android N and later applications can not share private files by name, try to share "File: // " URI of the cause will lead to FileUriExposedException. If your applications need to share private documents with other applications, it can FileProvider used in conjunction with FLAG_GRANT_READ_URI_PERMISSION in Android 6.0(API level 23) and on a lower level, if you file mode is set to world readable, other applications can read your internal documents. However, other applications need to know your application package name and file name. Unless you explicitly set a file to be read or written, or other applications can not browse your internal directory and does not read or write permissions · Therefore, as long as you use MODE_PRIVATE mark on the inside to store your files, other applications on never be able to access them. Write a cache file if you need to cache files, you should use createTempFile (). For example, the following method to extract the file name from the URL, and create a file with that name within the cache directory of the application: Private File getTempFile (Context context, String url) {File File; the try {String fileName = Uri.parse ( URL) .getLastPathSegment (); File = the File.createTempFile (fileName, null , context.getCacheDir ());} the catch (IOException E) { // Error the while Creating File } returnfile;} using the createTempFile () creates a file in the application-specific cache directory. You should delete files you no longer need on a regular basis. Note: If the system memory is low may delete cached files without warning, so be sure to check whether a file exists in the cache before reading. Open an existing file to be read existing files, call openFileInput (name), pass the file name. You can get an array of all fileList application file name by calling (). Note: If you need to package a file accessible when you install the application, save the file in your project's res / raw / directory. You can use openRawResource () pass the resource ID to open these files. This method returns the method can be used to read the file. You can not write the original file. Open a directory that you can use the following method to open a directory on the internal file system: getFilesDir (): Returns the File represent uniquely associated with your application directory on the file system. getDir (name, mode): Create a unique file system in the application's directory in a new directory (or open an existing directory). This new directory in the catalog getFilesDir provided (). getCacheDir (): Returns the File represents the file system uniquely associated with your application cache directory. This applies to temporary files directory, it should be cleaned regularly. If disk space is insufficient, the system may delete the files there, so make sure to check whether a file exists in the cache before reading. To create a directory in which the new file, you can use the File () constructor, passing an object designated internal storage directory of one of the above methods File provided. For example: File Directory = context.getFilesDir (); File File = new newFile (directory, filename); saved on an external storage file using an external memory is for you to share with other applications or allow users to use the computer to access files. After requesting permission to store and verify the memory available, you can save two different types of documents: Public documents: documents should be available to other applications and users free of charge. When users uninstall your application, these documents should still be available to users. For example, an application or other download files captured photos should be saved as public documents. Private documents: legal files in your application, the user will be deleted when you uninstall the application. Although technically these files by users and other applications to access because they are located on external storage, but they do not provide value to users outside of the application. Note: If you remove the SD card or connect the device to a computer, an external storage may become unusable. And users and other applications with READ_EXTERNAL_STORAGE permission can still see these files. Therefore, if the functionality of your application depends on these files, or you need to completely restrict access, you should write a file to the internal storage. Request permission to write to external storage common external storage, you must request the WRITE_EXTERNAL_STORAGE permission in the manifest file: <uses-permission android: name = "android.permission.WRITE_EXTERNAL_STORAGE" /> If your application uses the WRITE_EXTERNAL_STORAGE permission, it also implicitly has permission to read external storage. If your application only needs to read the external memory (but not write), then you need to declare READ_EXTERNAL_STORAGE permission: <uses-permission android: name = "android.permission.READ_EXTERNAL_STORAGE" />From Android 4.4 (API level 19) began to read in private external storage directory of the application or write to a file - use getExternalFilesDir () access, you do not need READ_EXTERNAL_STORAGE or WRITE_EXTERNAL_STORAGE permission. So, if your application supports 4.3 Android (API level 18) and earlier, and you only want to access dedicated external storage directory, you should request permission by adding maxSdkVersion property declaration only on an earlier version of Android: <uses- Android permission: name = "android.permission.WRITE_EXTERNAL_STORAGE" Android: maxSdkVersion = "18 is" /> verify that the external memory is available since the external storage may not be available - for example, when the user PC storage means is mounted or removed to provide an external storage SD card - you should always verify that the volume is available before the visit. You can query an external storage status getExternalStorageState by calling (). If the return status is MEDIA_MOUNTED, you can read and write files. If MEDIA_MOUNTED_READ_ONLY, you can only read the file. For example, the following methods can be used to determine available storage: / * Checks The External Storage IS IF Available for Read and Write * / public Boolean isExternalStorageWritable () {String 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;} Public directory saved to an external common method if you want to save the file in the external storage, use the getExternalStoragePublicDirectory () Get File indicates that the corresponding directory on the external storage. The method accepts a parameter that specifies the type of file to be saved, so that the public can use other file (e.g. DIRECTORY_MUSIC or) its logical organization DIRECTORY_PICTURES. For example: public File getPublicAlbumStorageDir (String ALBUMNAME) { // the Get The Directory User apos for public Pictures The File Directory File =. New new File (Environment.getExternalStoragePublicDirectory (Environment.DIRECTORY_PICTURES), ALBUMNAME); IF (! File.mkdirs ()) { Log.e (LOG_TAG, "Directory Not Created" );} returnfile;} If you want to hide files in Media Scanner, include a named external file directory .nomedia empty file (please note the prefix in the filename). This prevents the media scanner to read your media files, and by MediaStore content providers make it available to other applications. Saving to external private directory on the external storage can not MediaStore visit if you want to save the file in an application-specific and external providers, and you can pass it a name by calling getExternalFilesDir () to get a directory that only by your application usage, indicating the name of the directory you want to type. In this way, each created directory will be added to the parent directory, the directory encapsulates all external storage file for the application, it will be deleted when the user uninstall the application. public File getPrivateAlbumStorageDir (the Context context, String ALBUMNAME) { // the Get The App apos The Private Directory for File Directory File = Pictures. new new File (context.getExternalFilesDir (Environment.DIRECTORY_PICTURES), ALBUMNAME); IF (! file.mkdirs ()) Log.e {(LOG_TAG, "Directory not the Created" );} return file;} if there is no predefined subdirectory name for your file, you can call getExternalFilesDir () and pass null. This will return the root directory on an external storage application's private directory. Remember, getExternalFilesDir () to create a deleted when the user uninstalls the application directory. If you save a file after the user uninstalls the application is still available - for example, when your application to capture photos and the user should retain these pictures - you should save the file to a common directory. Selecting between a plurality of storage locations sometimes, internal partitions to allocate memory device as an external memory SD card slot is also provided. This means that the device has two different external storage directory, so you need to choose which directory to use when the "private" files written to the external memory. Android 4.4 from the start (API level 19), you can visit the two locations getExternalFilesDirs by calling (), which returns File position array containing each storage location entry. The first entry in the array is regarded as the main external storage, you should use this position unless it is full or unavailable. If your app supports Android 4.3 and earlier, you should use the static method supports the library ContextCompat.getExternalFilesDirs (). It always returns an array of File, but if the device is running Android 4.3 and earlier, so it contains only one main external storage entries (if there is a second storage location, you can not in Android 4.3 and earlier access it on). You should always delete files delete files your application is no longer needed. The most direct way to delete a file is to call the File object delete () method. myFile.delete (); if the file is saved on the internal memory, you can also find and delete files by calling deleteFile Context of (): myContext.deleteFile (fileName); Note: When you uninstall your application, Android system delete the following: all the files you saved on the internal memory. Use getExternalFilesDir () in the external storage of all files, however, you should manually delete getCacheDir () on a regular basis to create all cache files, and other documents periodically deletes no longer needed. Android catalog summary ($ RootDir) + - / the Data -> Environment.getDataDirectory () | | | | ($ appDataDir) | + - the Data / com.srain.cube.sample | | | | ($ FILESDIR) | + - Files -> Context.getFilesDir () / Context.getFileStreamPath ( "" ) | | | | | + - file1 -> Context.getFileStreamPath ( "file1" ) | | ($ cacheDir is) | + - Cache -> Context.getCacheDir () | | | + - app_ $ name -> (Context.getDir (String name, int the MODE) | | ($rootDir) +- /storage/sdcard0 -> Environment.getExternalStorageDirectory() | / Environment.getExternalStoragePublicDirectory("") | +- dir1 -> Environment.getExternalStoragePublicDirectory("dir1") | | ($appDataDir) +- Andorid/data/com.srain.cube.sample | | ($filesDir) +- files -> Context.getExternalFilesDir("") | | | +- file1 -> Context.getExternalFilesDir("file1") | +- Music -> Context.getExternalFilesDir(Environment.Music); | +- Picture -> ... Environment.Picture | +- ... | | ($cacheDir) +- cache -> Context.getExternalCacheDir() | +- ???

Guess you like

Origin www.cnblogs.com/Free-Thinker/p/11937620.html