首页 > 代码库 > Saving Files 保存文件
Saving Files 保存文件
Saving Files
保存文件
This lesson teaches you to
- Choose Internal or External Storage 选择内部或者外部存储
- Obtain Permissions for External Storage 为外部存储获取权限
- Save a File on Internal Storage 在内部存储保存一个文件
- Save a File on External Storage 在外部存储保存一个文件
- Query Free Space 查询空闲空间
- Delete a File 删除文件
You should also read
您还应该阅读
- Using the Internal Storage 使用内部存储
- Using the External Storage 使用外部存储
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 theFile
APIs.
安卓系统使用的文件系统类似于其他平台上的基于磁盘的文件系统。这节课描述了Android如何使用文件系统来读取和写入File
的API。
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.
一个File对象是适合于从头到尾的顺序不跳过地阅读或编写大量的数据提供。例如,有利于图像文件或任何通过网络交换的文件。
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 injava.io
.
这节课展示了如何在您的应用程序中执行基本与文件相关的任务。这个课程可以使您熟悉基本的Linux文件系统和在injava.io
中的标准文件输入/输出的API。
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, seeApp Install Location.
外部存储是存储文件最好的地方,不需要访问限制,你想与其他应用程序共享的文件或允许用户访问都可以。
提示:尽管应用程序安装到内部存储在默认情况下,您可以指定android: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 yourmanifest file:
写外部存储,您必须在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 aFile
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 theFile()
constructor, passing theFile
provided by one of the above methods that specifies your internal storage directory. For example:
其中的一个目录中创建一个新文件,您可以使用File()构造函数,通过上述方法之一提供的File方法,指定您的内部存储目录。例如:
File file = new File(context.getFilesDir(), filename);
Alternatively, you can call openFileOutput()
to get aFileOutputStream
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 usecreateTempFile()
. For example, the following method extracts the file name from aURL
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 toMEDIA_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 thegetExternalStoragePublicDirectory()
method to get aFile
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
orDIRECTORY_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.
如果你想要私人的文件保存到您的应用程序,您可以通过调用getExternalFilesDir()方法获得适当的目录和通过它的名字显示你想要的类型的目录。这种方式创建的每个目录添加到父目录,封装了应用程序的所有外部存储文件,系统删除当用户卸载应用程序。
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 callgetExternalFilesDir()
and passnull
. 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 usegetExternalStoragePublicDirectory()
.
记住getExternalFilesDir()创建一个目录在一个目录,当用户删除卸载应用程序。如果你保存的文件应该保持可用用户卸载后app-such当你的应用程序是一个相机和用户想保持photos-you应该使用getExternalStoragePublicDirectory()。
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.
无论您使用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 anIOException
by callinggetFreeSpace()
orgetTotalSpace()
. 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 bygetFreeSpace()
. 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 anIOException
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 calldelete()
on itself.
您可以删除不再需要的文件。最直截了当的方式,删除一个文件,打开文件引用调用delete()。
myFile.delete();
If the file is saved on internal storage, you can also ask theContext
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:
注意:当用户卸载应用程序,Android系统删除以下:
- All files you saved on internal storage 你保存在内部存储的所有文件
- All files you saved on external storage using
getExternalFilesDir()
. 所有使用getExternalFilesDir()方法保存在外部存储的文件
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()方法创建的缓存文件并定期删除你不再需要其他文件。