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

android数据存储_外部存储

2014-05-02 23:43 309 查看
源码下载(免下载积分):下载

外部存储并不是一定可以访问的,例如外部存储挂载到电脑上是,或者是SD Card作为外部存储,被移除是,因此在访问外部存储时,一定要保证外部存储是可以获得的。判断外部存储是否已经挂载到了手机上可以这样判断:

//判断外部存储是否可以访问,并且可以读写
private boolean isExternalStorageWritable()
{
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}

对于在外部存储的存储方式:

public files:文件可以被其他应用程序访问,并且在卸载应用程序以后会被删除

private files:卸载应用程序后,文件会被删除,

public files
创建并写入数据:

private void createPublicFile() {
//1. 判断是否外部存储可以访问
if (isExternalStorageWritable()) {
/*
*2. 使用getExternalStoragePublicDirectory方法来创建一个文件路径
* getExternalStoragePublicDirectory()方法会在外部存储中获得恰当的文件目录
* 参数表示的是文件的类型,DIRECTORY_PICTURES,DIRECTORY_DOWNLOADS等
*/
publicPath = new File(Environment.getExternalStoragePublicDirectory
(Environment.DIRECTORY_PICTURES), "myPictures");
//3.创建文件
publicFile = new File(publicPath,"1.png");
if (!publicPath.exists()) {
//创建此抽象路径名指定的目录,包括所有必需但不存在的父目录
if (!publicPath.mkdirs()) {
//这里抛出异常
throw new RuntimeException("不能创建所需目录");
}
}
//4. 向文件中写入数据
InputStream read = null;
FileOutputStream write = null;
try {
//Open a data stream for reading a raw resource
read = getResources().openRawResource(R.drawable.ic_launcher);
write = new FileOutputStream(publicFile);
byte[] data = new byte[read.available()];
//读取数据到data数组中
read.read(data);
write.write(data);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
try {
if (read != null)
read.close();
if (write != null)
write.close();
} catch (IOException e) {

e.printStackTrace();
}
}
//5. 告诉media scanner创建了新文件,目的为了使用户能立刻可以访问
MediaScannerConnection.scanFile(this,
new String[]{ publicFile.toString()}, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String publicPath, Uri uri) {
Log.e("public External Storeage", " Scanned "+publicPath+":");
Log.e("public External Storeage", " uri "+uri);
}
}
);
}
}


private files
其创建流程与public files的相同,只是在创建文件路径时使用的是getExternalFilesDir()

(这个是Context方法)方法

对于文件的删除,外部存储直接调用myFile.delete(),而对于内部存储的方式,就要调用

context.deleteFile(fileName);
对于在外部存储中创建缓存文件,可以调用getExternalCacheDir()方法,
权限:

对于外部存储应该添加相关的权限例如写数据:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

但对于android 4.4如果把文件存储为private files时不需要使用相关的权限

参考资料:

http://developer.android.com/training/basics/data-storage/files.html

http://developer.android.com/guide/topics/data/data-storage.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: