Saving Files

来源:互联网 发布:移动端关键词优化软件 编辑:程序博客网 时间:2024/05/17 23:04

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 FileAPIs.

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

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.
  • 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().

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.

外部存储:

  • 这并不总是可用,因为用户可以安装外部存储器作为USB存储 在某些情况下,从设备删除它。
  • 这是公开的,所以 文件保存在这里可以阅读你的控制之外。
  • 当用户卸载应用程序,系统删除应用程序的文件 只有如果你拯救他们的目录getExternalFilesDir()

外部存储器是最好的 地方文件,不需要访问限制,你想要分享的文件 与其他应用程序或允许用户访问计算机。


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.

提示:虽然应用程序安装到内部存储器 默认情况下,您可以指定android:installLocation在你的清单,这样你的应用程序可能属性 被安装在外部存储器。 用户欣赏这个选项当APK文件大小是非常大的和 他们有一个外部比内部存储的存储空间。 更多的 信息,请参阅应用程序安装位置

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.

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.

然而,如果您的应用程序使用WRITE_EXTERNAL_STORAGE许可,那么含蓄也允许读取外部存储器。

你不需要任何权限保存文件内部 存储。 应用程序总是阅读和许可 写文件在其内部存储目录。


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.
getFilesDir()返回一个文件代表一个内部为您的应用程序目录。

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.
getCacheDir()
返回一个文件代表一个内部程序的临时目录 缓存文件。 一定要删除这不是每个文件一次 不再需要和实现一个合理的大小限制为使用在任何给定的内存数量 时间,如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 = 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:

因为外部存储器可能unavailable-such当用户已经安装 存储到电脑或消除了SD卡,提供外部storage-you 之前应该确认体积可以访问它。 你可以查询外部 通过调用存储状态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_MUSICDIRECTORY_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.

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

如果你想要私人的文件保存到您的应用程序,您可以获得的 通过调用适当的目录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.

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 usegetExternalStoragePublicDirectory().

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.

如果没有一个预定义的子目录名称适合您的文件,您可以调用getExternalFilesDir()并通过null。 这 返回应用程序的根目录的私人在外部存储目录。

记住,getExternalFilesDir()删除目录下创建一个目录,当用户卸载应用程序。 如果你保存的文件应该保持用户卸载后可用 app-such当你的应用程序是一个摄像头,用户想要保持photos-you 应该使用getExternalStoragePublicDirectory()

不管你是否使用getExternalStoragePublicDirectory()文件共享的或getExternalFilesDir()私人的文件你的应用,你使用的是很重要的 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.

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.

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通过调用getFreeSpace()getTotalSpace()。 这些方法提供当前可用空间和 分别总空间存储卷。 这些信息也是有用的,以避免填充 存储容量超过一定阈值。

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

注意:你不需要检查的可用空间 在你保存你的文件。 你可以试着写文件,然后 抓住一个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.

你应该删除不再需要的文件。 删除一个最直接的方法 文件打开的文件引用调用删除()在本身。

myFile.delete();

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

如果文件是保存在内部存储,你也可以问上下定位和 通过调用删除一个文件deleteFile():

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

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.


注意:当用户卸载应用程序,Android系统删除 以下几点:

  • 你保存在内部存储的所有文件
  • 所有文件保存在外部存储使用getExternalFilesDir()

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


getCacheDir()
返回一个文件代表一个内部程序的临时目录 缓存文件。 一定要删除这不是每个文件一次 不再需要和实现一个合理的大小限制为使用在任何给定的内存数量 时间,如1 mb。 如果系统开始运行低存储、删除缓存文件 没有警告。
0 0
原创粉丝点击