Saving Files on External Storage 在外部存储保存文件

来源:互联网 发布:淘宝商品列表 编辑:程序博客网 时间:2024/05/18 09:22

Save a File on External Storage


Because the external storage may be unavailable—such as when the user has mounted thestorage to a PC or has removed the SD card that provides the external storage—youshould always verify that the volume is available before accessing it. You can query the externalstorage state by calling getExternalStorageState(). If the returnedstate is equal toMEDIA_MOUNTED, then you can read andwrite your files. For example, the following methods are useful to determine the storageavailability:

因为外部存储可能无法使用例如,当用户已经安装thestorage到PC或已删除SD卡,可提供外部存储成规应始终确保在卷可访问它。你可以通过调用getExternalStorageState查询externalstorage状态。如果returnedstate等于MEDIA_MOUNTED那么你可以阅读andwrite您的文件例如,下面的方法是有用的,以确定storageavailability

/* 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 twocategories of files you might save here:

Public files
Files thatshould 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 a File representingthe appropriate directory on the external storage. The method takes an argument specifyingthe type of file you want to save so that they can be logically organized with other publicfiles, 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 theappropriate directory by callinggetExternalFilesDir() and passing it a name indicatingthe type of directory you'd like. Each directory created this way is added to a parentdirectory that encapsulates all your app's external storage files, which the system deletes when theuser 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 callgetExternalFilesDir() and passnull. Thisreturns 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 yourapp—such as when your app is a camera and the user will want to keep the photos—youshould 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 usedirectory names provided by API constants likeDIRECTORY_PICTURES. These directory names ensurethat the files are treated properly by the system. For instance, files saved in DIRECTORY_RINGTONES are categorized by the system media scanner as ringtonesinstead of music

如果没有预先定义的子目录名称适合您的文件,您可以改为调用getExternalFilesDir ( ),并传递null 。Thisreturns上的外部存储您的应用程序的私有目录的根目录。

请记住, getExternalFilesDir ()创建当用户卸载时被删除目录内的某个目录app.If要保存文件的用户卸载yourapp ,比如当你的应用程序是一个摄像头,用户会想后应保持可用保持照片 - 成规,而不是使用getExternalStoragePublicDirectory ( ) 。
不管你是否使用getExternalStoragePublicDirectory ( )中是否有共享orgetExternalFilesDir ()对于那些私有您的应用程序文件的文件,它是你usedirectory通过API常量likeDIRECTORY_PICTURES提供的名字是非常重要的。这些目录名ensurethat的文件被系统妥善处理。例如,保存在DIRECTORY_RINGTONES文件由系统媒体扫描器归类为音乐的ringtonesinstead

Query Free Space


If you know ahead of time how much data you're saving, you can find outwhether sufficient space is available without causing anIOException by callinggetFreeSpace() orgetTotalSpace(). These methods provide the current available space and thetotal space in the storage volume, respectively. This information is also useful to avoid fillingthe storage volume above a certain threshold.

However, the system does not guarantee that you can write as many bytes as areindicated bygetFreeSpace(). If the number returned is afew MB more than the size of the data you want to save, or if the file systemis 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 spacebefore you save your file. You can instead try writing the file right away, thencatch anIOException if one occurs. You may need to dothis if you don't know exactly how much space you need. For example, if youchange the file's encoding before you save it by converting a PNG image toJPEG, you won't know the file's size beforehand

如果你提前知道有多少数据要保存,你可以找到outwhether足够的可用空间,而不会导致一个IOException通过调用getFreeSpace ( )或getTotalSpace ( ) 。这些方法提供了在所述存储卷中的当前可用空间和thetotal空间,分别为。此信息也有助于避免fillingthe存储量超过一定的阈值。

但是,系统不保证为areindicated由getFreeSpace (你可以写的字节数) 。如果返回的数字是AFEW MB的比你想保存,或者如果该文件systemis低于90 %满,那么它可能是安全的proceed.Otherwise的数据的大小更多,你可能不应该写入存储。
注:要检查可用spacebefore你保存文件的数量你是不是必需的。相反,您可以尝试写文件的时候了,如果发生thencatch一个IOException 。您可能需要dothis ,如果你不知道你到底需要多少空间。例如,如果您通过转换PNG图像toJPEG储存前友成文件的编码,你不会知道文件的大小事先

Delete a File


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

myFile.delete();

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

myContext.deleteFile(fileName);

Note: When the user uninstalls your app, the Android system deletesthe 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 withgetCacheDir() on a regular basis and also regularly deleteother files you no longer need.


0 0
原创粉丝点击