Android中内部存储和外部存储

内存及sdcard相关知识概述
  * RAM:运行内存,相当于电脑的内存
  * ROM:内部存储空间,相当于电脑的硬盘
* Android手机必须有的
  * SD卡:外部存储空间,相当于电脑的移动硬盘
* 不是必须的
  * 现在手机自带的空间都属于外部存储,然后手机基本内部外部共享同一个存储设备


  ###内部存储路径
  * 所有安装至手机的应用都会在data/data目录下生成一个包名文件夹,这个文件夹就是内部存储的路径
  * 应用只能在自己的包名文件夹中读写文件
  ###外部存储路径
  2.2之前:sdcard
  2.2~4.2:mnt/sdcard

  4.3开始:storage/sdcard


内部存储api相关代码:

写入本地文件
确定文件名和路径
//File file = new File("data/data/com.itheima.rwinrom/info.txt");//手写内部存储路径
//返回一个File对象,封装的路径是data/data/com.itheima.rwinrom/files
//File file = new File(getFilesDir(), "info.txt");//内存
//返回一个File对象,封装的路径是data/data/com.itheima.rwinrom/cache
File file = new File(getCacheDir(), "info.txt");//缓存
try {
FileOutputStream fos = new FileOutputStream(file);//文件输出流
//把账号密码写入本地文件
fos.write((name + "##" + pass).getBytes());
fos.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
读取文件,回显数据
// File file = new File("data/data/com.itheima.rwinrom/info.txt");
// File file = new File(getFilesDir(), "info.txt");
File file = new File(getCacheDir(), "info.txt");
if(file.exists()){
try {
FileInputStream fis = new FileInputStream(file);
//把字节流转换成字符流
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
//读取文件中的文本
String text = br.readLine();
} catch (Exception e) {
e.printStackTrace();
}
}


外部存储API相关代码
// File file = new File("sdcard/info.txt"); //手写外部存储路径,由于手机不同,可能不准确
//MEDIA_REMOVED:sd卡不存在
//MEDIA_UNMOUNTED:sd卡存在,但是没有挂载
//MEDIA_CHECKING:sd卡正在遍历
//MEDIA_MOUNTED:sd卡可用
//MEDIA_MOUNTED_READ_ONLY:sd卡可用,但是只读
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
//返回一个File对象,封装了外部存储的真实路径
File file = new File(Environment.getExternalStorageDirectory(), "info.txt");
try {
FileOutputStream fos = new FileOutputStream(file);
//把账号密码写入本地文件
fos.write((name + "##" + pass).getBytes());
fos.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else{
Toast.makeText(this, "SD卡不可用", 0).show();
}




//File file = new File("sdcard/info.txt");
File file = new File(Environment.getExternalStorageDirectory(), "info.txt");
if(file.exists()){
try {
FileInputStream fis = new FileInputStream(file);
//把字节流转换成字符流
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
//读取文件中的文本
String text = br.readLine();
String s[] = text.split("&&");
//给输入框设置文本
et_name.setText(s[0]);
et_pass.setText(s[1]);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值