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.

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.

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

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
.

Obtain Permissions for 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>

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.

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

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.

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:

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:

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.

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:

/* 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:

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:

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.

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.

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

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.

时间: 2024-08-24 23:03:06

Saving Files的相关文章

Saving Files 保存文件

Saving Files 保存文件 PreviousNextGet started This lesson teaches you to Choose Internal or External Storage                   选择内部或者外部存储 Obtain Permissions for External Storage            为外部存储获取权限 Save a File on Internal Storage                        

Android学习笔记——保存文件(Saving Files)

Android设备有两种文件存储区域:   内部存储和外部存储 ("internal" and "external" storage). 这名字来自早期Android,那时大多数Android设备提供两种存储方式:内置的非易失的内存(内部存储)和可移动的存储例如micro SD卡(外部存储). 一些设备将永久内存分为内部和外部两部分,因此即使没有外部存储,依旧有两种存储空间.不管有没有外部存储,API的方法都是一样的.     内部存储: 始终都是可用的 保存的文件

Saving Data

http://www.cnblogs.com/gcg0036/p/4321278.html Saving Key-Value Sets: 如果想保存一个相对较小的key-values集合,可以使用 SharedPreferences API. SharedPreferences对象指向包含key-value对的文件,并且提供简单的读写方式.每个SharedPreferences文件均由框架管理,私人或共享均可使用. 可以保存任何简单类型的数据:boolean.float.int.long 和 s

Android关于保存数据(Saving data)

1.SharedPreferences(key-value) SharedPreferences保存的数据主要是类似于配置信息格式的数据,因此保存的数据主要是简单类型的键值对(key-value),它保存的是一个XML文件. (1)创建sharedPreferences的两种方法:getSharedPreferences(String name, int mode)----如果你需要通过一个标识(name)来区分不同的sharedPreferences文件 getPreferences(int

Oracle 学习之卸载Oracle 11g

Oracle 11g 安装完毕后,如果有卸载的需要.可以有如下方法: 手工删除Oracle安装时建立的各目录.文件等.这种方法对于Linux还算可行,但是Window版中涉及到服务.注册表等等.往往删除不干净. 使用安装目录$ORACLE_HOME/deinstall/下的 deinstall脚本. [[email protected] deinstall]$ ./deinstall Checking for required files and bootstrapping ... Please

Sublime Text 3下C/C++开发环境搭建

Sublime Text 3下C/C++开发环境搭建 之前在Linux Mint 17一周使用体验中简单介绍过Sublime Text. 1.Sublime Text 3安装 Ubuntu.Linux Mint的软件管理器中已经能够找到Sublime Text 3,直接安装即可.或者去官网下载.deb或tarball安装包,手动安装. 2.Package Control管理器 ST最吸引我的第一点就是这个非常棒的扩展管理器!安装方法也很简单,在ST中按Ctrl+`进入ST的控制台,然后去官网上将

64位Linux安装android开发IDE的全过程

首先特别感谢这个链接: http://www.androiddevtools.cn/ 提供了几乎所有的安卓开发需要用到的资源. 操作系统:CentOS 7. 一.android studio 这个折腾了一个下午,放弃了,有些墙暂时无法逾越.Windows倒是折腾出来了,可能是对Linux64位版本的支持不够吧. 二.Eclipse ADT 先去上面链接的网站ADT Bundle资源链接里下载了64位的Linux版本(先解决有无,再考虑优化). 三.Cannot run program “ 你的路

Android存储选择

最近翻译了一篇Android Developer上的文章,文章的原路径是Storage Options.这篇文章说的是Android中的存储选择. Android为我们提供了几种存储稳固的应用数据的选择.你选择的方法取决于你的具体的需求,例如数据是否应该是对于当前应用是私有的或者对于其他的应用是可访问的,还有你的数据需要多大的空间. 你的数据存储方式如下: Shared Preferences: 用key-value的方式存储基本的私有数据. Internal Storage:(内部存储) 在设

《R in Nutshell》 读书笔记(连载)

R in Nutshell 前言 例子(nutshell包) 本书中的例子包括在nutshell的R包中,使用数据,需加载nutshell包 install.packages("nutshell") 第一部分:基础 第一章 批处理(Batch Mode) R provides a way to run a large set of commands in sequence and save the results to a file. 以batch mode运行R的一种方式是:使用系统