Android文件存储详解

来源:互联网 发布:木工平面设计软件 编辑:程序博客网 时间:2024/05/18 00:33
【读写外部存储的几个前提】//*外部存储、SD卡、文件系统指的都是同一概念
==================================================
·添加系统权限:
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
·判断外部存储/SD卡是否就绪:
String state = Environment.getExternalStorageState();
if(state.equals(Environment.MEDIA_MOUNTED)){
Toast.makeText(MainActivity.this, "外存设备就绪!", Toast.LENGTH_SHORT).show();
}
·获取外存根路径:
File rootDirectory = Environment.getExternalStorageDirectory();
·熟悉JAVA的IO流操作





【几个特殊的目录】
==================================================
@十大公共预置目录:(根路径下)
·MUSIC文件夹:Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);——系统建议存放音乐
·PODCASTS件夹:Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PODCASTS);——系统建议存放博客相关文件
·RINGTONES文件夹:Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_RINGTONES);——系统建议存放铃声
·ALARMS文件夹:Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_ALARMS);——系统建议存放警告音
·NOTIFICATIONS文件夹:Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_NOTIFICATIONS);——系统建议存放通知音
·PICTURES文件夹:Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);——系统建议存放图片
·MOVIES文件夹:Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);——系统建议存放电影和视频
·DOWNLOADS文件夹:Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);——系统建议存放下载到的文件
·DCIM文件夹:Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);——系统建议存放照片
·DOCUMENTS文件夹:Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);——系统建议存放文档
----------------------------------------
@应用的私有数据目录:
·获取路径:File filesDir = getExternalFilesDir(null);
·指向/Android/data/包名/files目录:可在设置中清除数据,卸载时一并删除;
·能够被用户访问到;
----------------------------------------
@应用的私有缓存目录
·获取路径:File cacheDir = getExternalCacheDir();
·指向/Android/data/包名/Cache目录:可在设置中清除缓存,卸载时一并删除;
·能够被用户访问到;
----------------------------------------
PS:应用的【私有内部存储】空间
·/data/data/包名
·数据库和SharedPreferences文件将存放在此处
·用户和其它程序默认都无法访问




【代码演示】
==================================================
@读写文本(自建目录)
private void readText() {
FileInputStream fis = null;
try {
//定位到文件
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "1605" + File.separator + "log.txt");
if (!file.exists()) {
Toast.makeText(MainActivity.this, "目标文件不存在!", Toast.LENGTH_SHORT).show();
return;
}

//读入文件内容
fis = new FileInputStream(file);
byte[] bytes = new byte[1024];
int len = -1;
String result = "";
while ((len = fis.read(bytes)) != -1) {
String s = new String(bytes, 0, len);
result += s;
}

//显示内容
tv.setText(result);

} catch (Exception e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "发生了一些异常...", Toast.LENGTH_SHORT).show();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

public static boolean writeText(Context context, String dirPath, String fileName, String text, boolean append) {
//创建目标文件夹
File dirFile = createDir(dirPath);
if (dirFile == null) {
Toast.makeText(context, "创建文件夹失败!", Toast.LENGTH_SHORT).show();
return false;
}

//创建文本文件
File file = createFile(context, dirFile, fileName);
if (file == null) {
Toast.makeText(context, "创建目标文件失败!", Toast.LENGTH_SHORT).show();
return false;
}

//向文件中写入数据
byte[] bytes = new String(text).getBytes();
return writeFile(file, bytes, append);
}
----------------------------------------
@读写图片(公共预置目录)
public static Bitmap readBitmap(Context context, String dirPath, String fileName) {
FileInputStream fis = null;
try {
//定位目标文件
boolean exists = checkIfFileExists(dirPath, fileName);
if (!exists) {
Toast.makeText(context, "目标文件不存在!", Toast.LENGTH_SHORT).show();
return null;
}

File file = new File(dirPath + File.separator + fileName);
//读入内容并转化为图片
fis = new FileInputStream(file);

return BitmapFactory.decodeStream(fis);

} catch (Exception e) {
e.printStackTrace();
Toast.makeText(context, "异常:" + e.getMessage(), Toast.LENGTH_SHORT).show();
return null;
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

public static boolean writeBitmap(Context context, Bitmap bitmap, String dirPath, String fileName, Bitmap.CompressFormat format) {
FileOutputStream fos = null;
try {
//定义写出的目标文件
File file = null;
//创建目标文件夹
File dirFile = createDir(dirPath);
if (dirFile == null) {
return false;
}

//创建目标文件
file = createFile(context, dirFile, fileName);
if (file == null) {
return false;
}

//向目标文件输出内容
fos = new FileOutputStream(file, false);
bitmap.compress(format, 100, fos);
return true;
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(context, "异常:" + e.getMessage(), Toast.LENGTH_SHORT).show();
return false;
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
----------------------------------------
@读写普通文件(私有外存目录)
private void readVideo() {
FileInputStream fis = null;
ByteArrayOutputStream baos = null;
try {
//拿到目标文件
File file = new File(getExternalFilesDir(Environment.DIRECTORY_MOVIES).getAbsolutePath() + File.separator + "abc.mp4");
if (!file.exists()) {
Toast.makeText(MainActivity.this, "目标视频不存在!", Toast.LENGTH_SHORT).show();
return;
}

//从目标文件中读取数据
fis = new FileInputStream(file);
baos = new ByteArrayOutputStream();
byte[] bytes = new byte[1024];
int len = -1;
while ((len = fis.read(bytes)) != -1) {
baos.write(bytes, 0, len);
}
byte[] videoBytes = baos.toByteArray();

//显示数据属性
tv.setText("视频的长度为:" + videoBytes.length + "字节");
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "异常:" + e.getMessage(), Toast.LENGTH_SHORT).show();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}

if (baos != null) {
try {
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

private void writeVideo() {
InputStream is = null;
FileOutputStream fos = null;
ByteArrayOutputStream baos = null;
try {
//模拟拿到下载的视频文件
is = getAssets().open("abc.mp4");

//创建目标文件
/**
* 类型如果为null则表示/Android/data/包名/files
* 类型如果为Environment.DIRECTORY_MOVIES,则表示/Android/data/包名/files/Movies
*/
File dirFile = getExternalFilesDir(Environment.DIRECTORY_MOVIES);
File file = new File(dirFile.getAbsolutePath() + File.separator + "abc.mp4");
if (file.exists()) {
file.delete();
} else {
boolean newFile = file.createNewFile();
if (!newFile) {
Toast.makeText(MainActivity.this, "创建目标文件失败!", Toast.LENGTH_SHORT).show();
return;
}
}

//向目标文件写入数据
fos = new FileOutputStream(file);
//1、将输入流转化为bytes
baos = new ByteArrayOutputStream();
byte[] bytes = new byte[1024];
int len = -1;
while ((len = is.read(bytes)) != -1) {
baos.write(bytes, 0, len);//将小水桶中的内容倒入大水缸
}
byte[] videoBytes = baos.toByteArray();

//2、向目标文件的fos灌装bytes
fos.write(videoBytes);
fos.flush();

} catch (Exception e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "异常:" + e.getMessage(), Toast.LENGTH_SHORT).show();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}

if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}

if (baos != null) {
try {
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}





【文件和流的核心API】
==================================================
·Environment.getExternalStorageDirectory()——拿到外部存储的根目录
·File.separator——兼容版的路径分隔符,即:"/"或"\",根据操作系统的不同而不同
----------------------------------------
·File file = new File(path);——根据路径创建文件对象(只是一个虚拟的File对象,不是文件实体)
·file.getAbsolutePath()——拿到文件的绝对路径
·boolean success = file.delete();——删除文件,返回值true代表删除成功
·boolean exists = file.exists();——判断文件是否存在
·boolean isDirectory = file.isDirectory();——判断文件是否为文件夹,true=是文件夹,否则为文件
·boolean success = file.createNewFile();——创建文件(地址自然为file所对应的地址)
·boolean success = dirFile.mkdirs();——创建文件夹(如路径很长则实际创建的是一连串的路径)
----------------------------------------
·FileInputStream fis = new FileInputStream(file);——拿到文件的输入流(以读入其内容)
·FileOutputStream fos = new FileOutputStream(file, true);——拿到文件的输出流(以向其中写出数据),true=以追加方式写入,false=以覆盖方式写入
·int length = inputStream.read(buffer);——将输入流中的数据倒入字节数组buffer中,并返回buffer的长度,如果长度为-1则表示没有倒入任何内容(即inputStream已经倒光)
·fos.write(bytes);——向文件输出流中写出数据
·fis.close();——用完之后关闭文件输入流
·fos.close();——关闭文件输出流
----------------------------------------
·ByteArrayOutputStream baos = new ByteArrayOutputStream();——新建字节数组输出流(以向其中写入byte[])
·baos.write(bytes, 0, len);——将缓冲区(小水桶)中的内容倒入字节数组输出流(大水缸)
·byte[] bytes = baos.toByteArray();——将字节数组输出流转化为字节数组
----------------------------------------
·Bitmap bitmap = BitmapFactory.decodeFile(filePath);——根据指定路径的图片解码为Bitmap对象
·Bitmap bitmap = BitmapFactory.decodeStream(inputStream);——将输入流解码为Bitmap对象
·Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher);——将图片资源解码为Bitmap对象
·boolean success = bitmap.compress(format, 100, fos);——将bitmap以format定义的格式、100的质量,写入文件输出流fos对应的文件中
----------------------------------------
·byte[] buffer = new byte[1024];——创建大小为1024字节的字节数组(作为读写缓冲区)
·byte[] bytes = str.getBytes();——拿到字符串的字节数组






















原创粉丝点击