在安卓系统中读写数据

0.安卓储存空间:

目录结构在FileExplorer中查看,可通过Windows/Show View/Others/FileExplorer打开
内部存储空间internal storage):自带的,必须有的

RAM内存:运行内存(电脑内存)
ROM内存:存储空间(电脑硬盘)

内部存储路径data/data/包名文件夹/

(包名文件夹需要部署才会生成)

外部存储空间external storage):SD卡(移动硬盘,可有可无)


1.在内部存储中读写文件

1)写文件相关代码;(不需要权限)
File file = new File("data/data/com.example.positionv1_1/tmp.txt");
FileOutputStream fileOutputStream;
try {
	fileOutputStream = new FileOutputStream(file);
	fileOutputStream.write("name".getBytes());
	fileOutputStream.close();	//应该写在finally中的
} catch (Exception e) {
	// TODO: handle exception
	e.printStackTrace();
}
2)读文件相关代码
FileInputStream fis;
try {
	fis = new FileInputStream(file);
	BufferedReader bReader =new BufferedReader(new InputStreamReader(fis));
	String string = bReader.readLine();
	String[] strings = string.split("##");
} catch (Exception e) {
	e.printStackTrace();
}
3)通过API获取路径,不用字符串表示
getFilesDir();//即data/data/包名文件夹/files
getCacheDir();//缓存文件夹,data/data/包名文件夹/cache;当内存不足时自动删除,1,重要信息不放;2,自己指定缓存阀值

//File如下定义
File file = new File(getFilesDir(),"tmp.txt")

2.在外部存储中读写文件

1)路径字符串表示

代码与内部一样,只是路径不一样

  • 2.2版本之前,SD卡路径:sdcard
  • 4.3版本之前,SD卡路径:mnt/sdcard
  • 4.4版本开始,SD卡路径:storage/sdcard

以上3中写法都可以

2)API获取路径
Environment.getExternalStorageDirectory();
3)相关权限

写SD卡需要权限:(权限在清单文件AndroidManifest.xml中加载)

<!-- 往SDCard写入数据权限 --> 
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

读不需要权限

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值