您的位置:首页 > 移动开发 > Android开发

Saving Files保存文件 官方文档翻译

2016-11-02 15:56 344 查看


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.
安卓使用的文件系统类似于其他平台的磁盘文件系统。本课介绍怎么使用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
.

这节课教你在app中如何使用文件相关的操作。这节课假定你已经熟悉了基本的linux文件系统和java.io中标准的文件输入/输出APIs。

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.

所有的安卓设备都有两个文件存储区域:“internal”和“external” 存储。这些命名来自早些的安卓,当时大多数的设备都提供了内嵌的非易失性的存储(内部存储),加上一个可以移除的存储介质比如micro SD卡(外部存储)。一些设备将永久存储器空间划分为内部和外部分区,所以甚至没有可移除的存储介质,它们也总是两个存储空间并且API的行为也是相同的不管外部存储是否是可以移除的。下面列表总结了关于每个存储空间的特点。

Internal storage:
It's always available.
Files saved here are accessible by only your app.
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.

总是可用的

文件保存之后只能被自己的app访问。

当你卸载你的app时,文件系统会删除你app所有的内部存储文件。

内部存储是最好的选择,这样可以确保用户和其他app都不能访问你的文件。

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存储并且在一些情况会移除外部存储。

它是可读的,所以保存在这里的文件可以被读取在你的控制之外。

当用户卸载你的app,系统只会删除你保存在getExternalFilesDir()目录的文件;

外部存储是不需要权限控制并且你可以和其他app共享文件或者允许用户使用计算机访问。

Tip: 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. 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.
提示:虽然app默认是安装到内部存储,但是你也可以在manifest文件中指定android:installLocation属性这样你的app可以安装到外部存储。

用户很喜欢这个选项,当然APK很大的时候并且外部存储空间比内部存储空间大的时候。了解更多信息,请看App安装位置。

Obtain Permissions for External Storage

获取外部存储权限

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

写内容到外部存储,你必须在manifest文件里设置WIRTE_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.

注意:当前,所有app是可以读取外部存储在没有权限的情况下。然而,在将来的版本会改变的。如果你需要读取外部存储(但不是写),你需要声明READ_EXTERNAL_STORAGE权限。为了确保你的app正常工作,你应该在改变之前声明权限。

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

然而,如果你的app使用了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.
为你的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.
返回一个表示你app临时文件缓存内部目录的文件。当你不在需要这些文件的时候确保每个文件都要删除并且要限制内存大小,例如1M。如果系统处于低内存的时候,它可能会在没有任何警告的情况下删除你的缓存文件。

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读取文件名并在你app内部缓存目录创建一个新文件:

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.

注意:在安卓文件系统中你app内部存储目录是由你的app的包名指定的。技术上,其他的app可以读取你的内部文件如果你设置文件的模式为可以读。然而,其他的app也需要知道你app的包名和文件名。其他的app不能浏览你内部目录并且不能读写,除非你设置这些文件可以读写。所以只要你使用MODE_PRIVATE模式了你在内部存储的文件其他app就不能访问。

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:

虽然用户和其他app可以修改外部存储,但是你也可以在这里存储两类文件:

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.
对于用户和其他app这些文件是自由可用的,当用户卸载了你的app,这些文件应该仍然可用。
For example, photos captured by your app or other downloaded files.
例如,app拍摄的照片或者下载的文件。
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.
正常情况下这些文件属于你的app,当用户卸载app的时这些文件应该被删除。虽然这些文件在技术上是可以被用户和其他app访问的因为他们在外部存储。这些文件不会向你app之外的用户提供价值。当用户卸载app,系统会删除所有存储在外部私有目录的文件。
For example, additional resources downloaded by your app or temporary media files.
例如,你app下载的额外资源或者临时媒体文件。

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 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()并且要指定一个目录名。通过这种方式的创建的目录会被添加到父目录下,当用户卸载app的时候系统会删除这个目录。

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息