Saving Files

来源:互联网 发布:u盘数据恢复大师免费版 编辑:程序博客网 时间:2024/06/07 14:58

Saving Files 保存文件

Android uses a file system that's similar to disk-based file systems on other platforms. This lesson describes how to work with the Android file system to read and write files with the File APIs.

安卓使用的文件系统类似于其他平台上的基于磁盘的文件系统。这节课描述了Android如何使用文件系统去用File APIs读写文件。

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.

一个文件对象是适合读或写大量的从头到尾的顺序的数据。例如,有利于图像文件或任何通过网络交换的文件。

This lesson shows how to perform basic file-related tasks in your app. The lesson assumes that you are familiar with the basics of the Linux file system and the standard file input/output APIs in java.io.

这节课展示了如何在你的应用程序里执行基本的与文件相关的任务。即假设您熟悉基本的Linux文件系统和java.io里标准文件的输入/输出。

Choose Internal or External Storage 选择内部或外部存储


All Android devices have two file storage areas: "internal" and "external" storage. These names come from the early days of Android, when most devices offered 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 the external storage is removable or not. The following lists summarize the facts about each storage space.

所有的Android设备有两个文件存储区域:“内部”和“外部”存储。这些名字来自Android的早期,当大多数设备提供了内置的非易失性存储器(内存),加上一个可移动的存储介质如微型SD卡(外部存储)。一些设备将永久存储空间划分为“内部”和“外部”分区,所以即使没有一个可移动的存储介质,也总有两种存储空间和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.当用户卸载你的应用程序,系统会从内部存储中删除所有你的应用的文件。

Internal storage is best when you want to be sure that neither the user nor other apps can access your files.内部存储是当你想确保无论是用户还是其他应用程序可以访问你的文件时的最好的方式。

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.它并不总是可用的,因为用户可以安装外部存储USB存储和在某些情况下从设备删除它。
  • 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()方法保存在目录中的文件

External storage is the best place for files that don't require access restrictions and for files that you want to share with other apps or allow the user to access with a computer.外部存储文件是最好的地方,当你想与其他应用程序共享的文件或允许用户通过计算机访问不需要访问限制

Tip: Although apps are installed onto the internal storage by default, you can specify theandroid:installLocation attribute in your manifest so your app may be installed on external storage. Users appreciate this option when the APK size is very large and they have an external storage space that's larger than the internal storage. For more information, see App Install Location.

提示:尽管应用程序在默认情况下安装到内部存储,你可以在你的属性清单文件中指定theandroid:installLocation属性,这样你的应用程序可以安装在外部存储器。用户欣赏这个选项,当APK文件大小是非常大而且他们有一个存储空间比内部存储的大得多的外部存储空间时。有关更多信息,请参见App Install Location。

Obtain Permissions for External Storage 获得外部存储权限


To write to the external storage, you must request the WRITE_EXTERNAL_STORAGE permission in your manifest file:

为了写入到外部存储,你必须在清单文件中请求WRITE_EXTERNAL_STORAGE权限:

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

Caution: Currently, all apps have the ability to read the external storage without a special permission. However, this will change in a future release. If your app needs to read the external storage (but not write to it), then you will need to declare the READ_EXTERNAL_STORAGE permission. To ensure that your app continues to work as expected, you should declare this permission now, before the change takes effect.

注意:目前,所有应用程序可以在没有特别权限情况下读取外部存储。然而,这将在将来发布的版本中改变。如果你的应用程序需要读取外部存储器(但不写),那么你将需要声明READ_EXTERNAL_STORAGE许可。确保应用程序可以继续正常工作,你现在应该声明这个许可,在改变生效前。

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

However, if your app uses the WRITE_EXTERNAL_STORAGE permission, then it implicitly has permission to read the external storage as well.然而,如果您的应用程序使用WRITE_EXTERNAL_STORAGE许可,那么它也可以读取外部存储器。

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.你在保存到内部存储的文件时不需要任何权限。应用程序总是允许在其内部存储目录中读取和写入文件。

Save a File on Internal Storage 在内部存储器保存一个文件


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.返回一个代表你的应用程序的内部目录的临时缓存文件。一旦不再需要和为你使用的内存数量实现一个合理的大小限制,一定要在任何给定的时间内删除每个文件,比如1 mb。如果系统开始运行低存储,它可能毫无预警地删除缓存文件。

To create a new file in one of these directories, you can use the File() constructor, passing the File provided by one of the above methods that specifies your internal storage directory. For example:

在其中的一个目录中创建一个新文件,您可以使用File()构造器,通过上述方法之一提供的文件,指定您的内部存储目录。

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

Alternatively, you can call openFileOutput() to get a FileOutputStream that writes to a file in your internal directory. For example, here's how to write some text to a file:

或者,你可以用openFileOutput()方法获得FileOutputStream在你的内部目录中写入一个文件。例如,下面是如何编写一些文本文件:

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, if you need to cache some files, you should instead use createTempFile(). For example, the following method extracts the file name from a URL and creates a file with that name in your app's internal cache directory:

或者,如果你需要缓存一些文件,您应该使用createTempFile()方法。例如,下面的方法从一个URL中提取文件的名字并创建一个文件,这个名字在你的应用程序的内部缓存目录:

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你的文件,他们将永远不会被其他应用程序访问

Save a File on External Storage 保存一个文件在外部存储器


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:

因为外部存储器可能不可用,比如当用户安装电脑的存储或删除了SD卡,提供外部存储,你应该验证是否可以在访问之前。你可以通过调用外部存储状态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;}

Although the external storage is modifiable by the user and other apps, there are two categories of files you might save here:

虽然外部存储由用户和其他应用程序修改,这里有两个类别的文件你可能保存:

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.例如,额外的资源下载应用程序或临时的媒体文件。

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或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;}

If you want to save files that are private to your app, you can acquire the appropriate directory by callinggetExternalFilesDir() 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.

如果你想要私有文件保存到您的应用程序,您可以由callinggetExternalFilesDir()获得适当的目录和通过它一个名称显示你想要的类型的目录。这种方式创建的每个目录添加到父目录,封装了应用程序的所有外部存储文件,系统删除当用户卸载应用程序。

For example, here's a method you can use to create a directory for an individual photo album:

例如,这里有一个方法可以用来创建一个目录的个人相册:

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.

如果没有一个适合你的文件的预定义的子目录名字,你可以通过getExternalFilesDir()和传递null。这将返回您的应用程序在外部存储目录上的根目录。

Remember that getExternalFilesDir() creates a directory inside a directory that is deleted when the user uninstalls your app. If the files you're saving should remain available after the user uninstalls your app—such as when your app is a camera and the user will want to keep the photos—you should instead use getExternalStoragePublicDirectory().

记住getExternalFilesDir()方法在一个目录中创建一个目录,当用户删除卸载应用程序。如果你保存的文件应该保持可用,在用户卸载后应用后,比如当你的应用程序是一个相机而且用户想要保持照片,你应该用getExternalStoragePublicDirectory()。

Regardless of whether you use getExternalStoragePublicDirectory() for files that are shared orgetExternalFilesDir() 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.

无论您是否使用getExternalStoragePublicDirectory(),orgetExternalFilesDir()私有方法到你的应用程序,重要的是你使用API提供的目录名如DIRECTORY_PICTURES常量。这些目录名确保文件被系统正确对待。例如,文件保存在DIRECTORY_RINGTONES目录下,是由系统分类媒体扫描仪的铃声,而不是音乐。

Query Free Space 查询空闲空间


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.

如果你知道提前保存多少数据,你可以找到是否有足够的空间可用而不会导致一个IOException,通过调用getFreeSpace()或getTotalSpace()。这些方法提供当前的可用空间和总空间存储。这些信息也是有用的,以避免填充存储体积超过一定值。

However, the system does not guarantee that you can write as many bytes as are indicated by getFreeSpace(). If the number returned is a few MB more than the size of the data you want to save, or if the file system is less than 90% full, then it's probably safe to proceed. Otherwise, you probably shouldn't write to storage.

然而,系统并不能保证你可以写尽可能多的字节被getFreeSpace()表示。如果返回的数字是几MB大小的超过你想保存的数据,或者文件系统还不到90%,那么它可能是安全的。否则,你可能不能写入存储。

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.

注意:您不需要在你保存文件前检查的可用空间。你可以试着写文件,然后抓住一个IOException。你可能需要这样做,如果你不知道你需要多少空间。举个例子,如果保存之前你改变文件的编码将PNG图像转换成JPEG,事先你不知道文件的大小。

Delete a File 删除一个文件


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

你应该删除不再需要的文件。最直截了当的方式,删除一个文件,打开文件引用调用delete()。

myFile.delete();

If the file is saved on internal storage, you can also ask the Context to locate and delete a file by calling deleteFile():

如果文件是保存在内部存储,你还可以用deleteFile()的Context来定位和删除一个文件:

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 using getExternalFilesDir().

注意:当用户卸载应用程序,Android系统删除以下内容:
 你保存在内部存储的所有文件。
 所有使用getExternalFilesDir()保存在外部存储的文件

However, you should manually delete all cached files created with getCacheDir() on a regular basis and also regularly delete other files you no longer need.

然而,您应该手动删除所有由getCacheDir()创建的缓存文件并定期删除你不再需要的其他文件。


0 0
原创粉丝点击