android文件存储分为内部存储 和 外部存储 ,区别是当卸载程序时,内部存储删除掉所有的相关信息。外部存储又分为共有区域和私有区域
当程序卸载时,共有区域上的数据不会被一同删除掉,只会删除掉根目录下的getExternalFilesDir()文件下数据,当我们操作外部区域时应加上
权限<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />其位置与application同级
内部存储读取数据:
一、采用内部存储读取数据时与Java基础中操作文件方式相同,只是获取路径的方法不同
二、采用openFileoutput(文件名,Context.MODE_PRIVATE)方法,方法已经默认了文件路径,只用加上路径下的文件名即可
1、getFilesDir() 获取文件绝对路径 2、getCacheFil() 获取缓存路径 两种方式获取的路径为两个不同的文件夹
外部存储读取数据:
在此之前应先检查外部存储是否可用
/*
* 检测外部储存是否可用,true为可用
* */
private boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (state.equals(Environment.MEDIA_MOUNTED)) {
return true;
} else {
return false;
}
}
其读取数据分为在公共区域和私有区域,主要方法有公共区域:Environment.getExternalStoragePublicDirectory()括号中为数据类型Environment.(点)(数据类型)
私有区域:getExternalFilesDir()括号中为数据类型Environment.(点)(数据类型)
下面以公共区域为例执行数据的读写操作 (点击时执行操作)
public void onClickInputFile(View v) { //xml中代码实现onclick
/*保存在外部公共区域*/
if (isExternalStorageWritable()) {
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.ddd);
File pathName = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)+"/"+
"ddd.jpg");
FileOutputStream fos;
try {
fos = new FileOutputStream(pathName);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
Toast.makeText(this, "读取完成", Toast.LENGTH_SHORT).show();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}else{
Logs.v("外部存储不可用");
}
}
将数据从文件中读到acitivity中显示
public void onClickOutputFile(View v) {
if (isExternalStorageWritable()) {
File pathName = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)+"/"+
"ddd.jpg");
Bitmap bitmap = BitmapFactory.decodeFile(pathName.getAbsolutePath());
mImageView.setImageBitmap(bitmap);
}else{
Logs.v("外部存储不可用");
}
}