android File存储

文件存储的用途:

A File object is suited to reading or writing large amounts of data in start-to-finish order without skipping around. For example, it's good for image files or anything exchanged over a network.(适用于无跳过方式读写大数据,如图像文件的读写,或者通过网络传递的交换数据)


存储介质的分类:

分为内部存储(internal storage)和外部存储(external storage),外部存储又分为两类,分别为可移动的外部存储(micro SD card)和不可移动的外部存储(和手机集成在了一起)

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 the external storage is removable or not. (不管外部存储是否可移动,api都是相同的)


内部存储和外部存储的区别:

Internal storage:

It's always available.(总是可用的)
Files saved here are accessible by only your app by default.(默认只有你的本应用可以访问)
When the user uninstalls your app, the system removes all your app's files from internal storage.(如果卸载了应用将移除所有该应用的文件)

External storage:

It's not always available, because the user can mount the external storage as USB storage and in some cases remove it from the device.(不总是可用的,因为通过use装载手机时外部存储就不可用了)
It's world-readable, so files saved here may be read outside of your control.(是全局可读的,非本应用也可访问到该应用的数据)
When the user uninstalls your app, the system removes your app's files from here only if you save them in the directory from getExternalFilesDir().(卸载应用时仅仅移除保存在通过getExternalFilesDir()方法获取到的目录内的文件)


android:installLocation属性:

Although apps are installed onto the internal storage by default, you can specify the android:installLocation attribute in your manifest so your app may be installed on external storage. (默认应用是安装在内部存储空间的,可以指定该属性在清单文件将应用保存在外部存储)


获取访问外部存储和内部存储的权限:

外部存储:

To write to the external storage, you must request the WRITE_EXTERNAL_STORAGE permission in your manifest file:(声明写外部存储的权限)

<manifest ...>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    ...
</manifest>
目前读外部存储不需要权限,将来会拓展该权限(可以提早声明以支持未来版本):

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

但是如果你声明了 WRITE_EXTERNAL_STORAGE permission,默认就包含了读取外部存储的权限。

内部存储:
You don’t need any permissions to save files on the internal storage. Your application always has permission to read and write files in its internal storage directory.(默认就有读取和写入内部存储的权限,不需要声明)

创建与删除文件的权限:

<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>


保存文件至内部存储:

1.When saving a file to internal storage, you can acquire the appropriate directory as a File by calling one of two methods:(第一步需要获取合适的目录调用如下方法之一):

getFilesDir()

Returns a File representing an internal directory for your app.(返回本应用代表的内部存储目录)
getCacheDir()

Returns a File representing an internal directory for your app's temporary cache files. Be sure to delete each file once it is no longer needed and implement a reasonable size limit for the amount of memory you use at any given time, such as 1MB. If the system begins running low on storage, it may delete your cache files without warning.(返回本应用代表的临时文件保存目录,该文件一旦不需要将会被删除,并使用合理的大小限制在给定的时间,如1M,如果系统存储过低时,将会删除这类文件而没有提醒)

2.通过File的构造函数创建一个文件:

File file = new File(context.getFilesDir(), filename);
或者使用便利api(通过该方法直接打开保存至内部存储的文件)如下:

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();
}
通过便利api保存至临时内部储存:

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;
}
Note: Your app's internal storage directory is specified by your app's package name in a special location of the Android file system. Technically, another app can read your internal files if you set the file mode to be readable. However, the other app would also need to know your app package name and file names. Other apps cannot browse your internal directories and do not have read or write access unless you explicitly set the files to be readable or writable. So as long as you use MODE_PRIVATE for your files on the internal storage, they are never accessible to other apps.(每个应用的内部存储通过包名进行唯一区分,其他应用能够读取你的应用的内部存储在你的文件读写模式设置为可读或可写的情况,而且必须还要知道该应用的包名和文件名,如果设置为MODE_PRIVATE将不能被其他应用读写)

保存文件至外部存储:

1.Because the external storage may be unavailable—such as when the user has mounted the storage to a PC or has removed the SD card that provides the external storage—you should always verify that the volume is available before accessing it. You can query the external storage state by calling getExternalStorageState(). If the returned state is equal to MEDIA_MOUNTED, then you can read and write your files. For example, the following methods are useful to determine the storage availability(因为外部存储不总是可用的,所以使用它之前必须进行验证,通过调用getExternalStorageState()方法,返回MEDIA_MOUNTED代表可以进行读写):

/* Checks if external storage is 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;
}
2.外部存储的分类:

Public files
Files that should be freely available to other apps and to the user. When the user uninstalls your app, these files should remain available to the user.
For example, photos captured by your app or other downloaded files.(这类保存的文件将被本应用和其他应用使用,如某些照片捕获文件,或者通过网络下载的文件,这类文件在应用卸载时不应该被删除)
Private files
Files that rightfully belong to your app and should be deleted when the user uninstalls your app. Although these files are technically accessible by the user and other apps because they are on the external storage, they are files that realistically don't provide value to the user outside your app. When the user uninstalls your app, the system deletes all files in your app's external private directory.
For example, additional resources downloaded by your app or temporary media files.(这类文件仅仅被本应用使用,一般为特定某为该应用的配置文件等等,这类文件在本应用私有的,在该应用卸载时应该被删除)

3.保存公共的外部文件(一般指定为系统规定的路径):
If you want to save public files on the external storage, use the getExternalStoragePublicDirectory() method to get a File representing the appropriate directory on the external storage. The method takes an argument specifying the type of file you want to save so that they can be logically organized with other public files, such as DIRECTORY_MUSIC or DIRECTORY_PICTURES. For example(如果要保存公共的外部文件,通过调用getExternalStoragePublicDirectory(),并使用合适的参数如:DIRECTORY_MUSIC or DIRECTORY_PICTURES):

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;
}
4.保存私有外部文件(在该应用卸载时随应用将被删除):

If you want to save files that are private to your app, you can acquire the appropriate directory by calling getExternalFilesDir() and passing it a name indicating the type of directory you'd like. Each directory created this way is added to a parent directory that encapsulates all your app's external storage files, which the system deletes when the user uninstalls your app.()(通过调用getExternalFilesDir()方法,该目录被增加至该应用对应外部存储目录的根目录):

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 none of the pre-defined sub-directory names suit your files, you can instead call getExternalFilesDir() and pass null. This returns the root directory for your app's private directory on the external storage.(如果没有合适子目录的路径名,也可以指定null参数代表保存至本应用对应文件夹的根目录)
5.使用系统预定义变量创建目录名(不管是public files或者是private files):

Regardless of whether you use getExternalStoragePublicDirectory() for files that are shared or getExternalFilesDir() for files that are private to your app, it's important that you use directory names provided by API constants like DIRECTORY_PICTURES. These directory names ensure that the files are treated properly by the system. For instance, files saved in DIRECTORY_RINGTONES are categorized by the system media scanner as ringtones instead of music.


查询剩余可用空间:

If you know ahead of time how much data you're saving, you can find out whether sufficient space is available without causing an IOException by calling getFreeSpace() or getTotalSpace(). These methods provide the current available space and the total space in the storage volume, respectively. This information is also useful to avoid filling the storage volume above a certain threshold.(getFreeSpace()和getTotalSpace()查询可用空间和总的空间,以避免超出存储空间而造成IOException)

Note: You aren't required to check the amount of available space before you save your file. You can instead try writing the file right away, then catch an IOException if one occurs. You may need to do this if you don't know exactly how much space you need. For example, if you change the file's encoding before you save it by converting a PNG image to JPEG, you won't know the file's size beforehand.(你仅仅应该在写入文件之前获取可用空间,因为也许你会改变文件的编码或者转换成特定的格式,因此你不知道文件的大小在写入外部存储之前)

删除文件:

删除外部存储文件:

myFile.delete();

删除内部存储文件:

myContext.deleteFile(fileName);

Note: When the user uninstalls your app, the Android system deletes the following(卸载应用时将删除如下文件):

  • All files you saved on internal storage
  • All files you saved on external storage usinggetExternalFilesDir().

However, you should manually delete all cached files created withgetCacheDir()on a regular basis and also regularly delete other files you no longer need.(注意,你必须手动删除保存至getCacheDir()的缓存文件)


常用api:

打开文件的模式:

MODE_PRIVATE:该文件只能被当前程序读写。

MODE_APPEND:以追加方式打开该文件,应用程序可以向该文件中追加内容。

MODE_WORLD_READABLE:该文件的内容可以被其他程序读取。

MODE_WORLD_WRITEABLE:该文件的内容可由其他程序读,写。

Context还提供了如下方法访问应用程序的数据文件夹:

getDir(String name,int mode):在应用程序的数据文件夹下获取或创建name对应的子目录

File getFilesDir():获取该应用程序的数据文件夹的绝对路径

String[] fielList():返回该应用程序的数据文件夹下的全部文件

deleteFile(String):删除该应用程序的数据文件夹下的指定路径


你可能感兴趣的:(android)