1、 android的数据保存在系统内存中:
getFilesDir()方法是父类提供的方法可以直接访问 data/data/包名/files目录
File file = new File(getFilesDir(), “info.txt”);
// 可以判断该文件存不存在。
if(file.exists){
// openFileInput(String)是父类提供的方法,
//可以直接获取 data 目录下指定文件的的输入流
FileIputStream fis= openFileInput(“info.txt”);
//将文件输入流转化为缓存流
BufferedReader bf = new BufferedReader(new InPutStreamReader(fis));
//因为保存时数据只有一行,因此读取一次就可以
String readLine = bf.readLine();
bf.close();
}else{
//从网络上得到一个输入流
InputStraem in=
boolean isNew=writeDatesTOSDCard(file,in);
//没有此文件将网络文件写入到这个目录下。
}

/**
* @param file 文件
* @param inputStream 输入流
* @return 是否成功写入
*/
public static boolean writeDatesToSDCard(File file,InputStream inputStream){
boolean flag=true;
FileOutputStream fos=null;
try {
fos=new FileOutputStream(file);
byte[] buf = new byte[4096];
int ch = -1;
while ((ch = inputStream.read(buf)) != -1) {
fos.write(buf, 0, ch);
}
} catch (IOException e) {
flag=false;
e.printStackTrace();
}finally {
try {
if (fos != null) {fos.close();}
}catch (Exception e){
e.printStackTrace();
}
}
return flag;
}
注意:
上面使用到了如下方法,这些方法都是在 ContextWrapper类中定义的,是 Activity 的父类,因此可以
直接使用。
getFilesDir():直接获取 /data/data/包名/files 文件
openFileInput(“info.txt”):直接打开/data/data/包名/files/info.txt 文件
openFileOutput(“info.txt”, MODE_PRIVATE):直接创建 /data/data/包名/files/info.txt 文件
在开发过程中凡是涉及到 data 目录操作的,很少自己去创建输入流和输出流,而应该尽量去使用
Google 已经提供的方法。
openFileOutput(“info.txt”, MODE_PRIVATE)方法的第二个参数是设置文件的权限,这里使用了私有常
量值,也就是只能当前应用访问该文件。

2.android的数据保存在没存卡中
//通过 Environment 工具类提供的方法获取 sdcard根路径
File file = new File(Environment.getExternalStorageDirectory(), “info.txt”);
//实现数据的回显
if (file.exists()) {
try {
FileReader reader = new FileReader(file);
BufferedReader bf = new BufferedReader(reader);
String readLine = bf.readLine();
bf.close();
} catch (Exception e) {
e.printStackTrace();
}
}else{//不存在 则创建此文件。写入内容
FileWriter writer = new FileWriter(file);
writer.write(“content”);
writer.close();
}

注意:
在 上 面 的 代 码 中 使 用 了 一 个 Environment 的 工 具 类 , 该 类 提 供 了 一 个 静 态 方 法
getExternalStorageDirectory可以直接返回 sdcard 的根目录, 因此我们在写代码的时候一定不要将该路
径“写死”。

最后: 添加权限
该案例中我们对 sdcard 进行了读写操作,sdcard 是受保护的目录,因此需要在 AndroidManifest.xml
中声明权限。

更多相关文章

  1. Android设备开机后自动启动APP解决方法:(学习篇)
  2. Android 文字自动滚动(跑马灯)效果的两种实现方法[特别好使]
  3. Android Fragment 生命周期及回调方法
  4. 部分 CM11 系统 Android 平板执行植物大战僵尸 2 黑屏的解决的方
  5. Android 在Service开启对话框的方法
  6. Fiddler 跟踪 Android 数据包
  7. 理解 Android 本地数据存储 API
  8. Android React Native在Android Studio中执行bundleReleaseJsAnd
  9. Android圆角按钮的制作方法

随机推荐

  1. Python工程师需要掌握的面试题
  2. 一个有参装饰器,它可作用于任何函数上
  3. RAID原理分析总结-运维工作记录-51CTO博
  4. Python-pip安装包下载慢,怎么办?
  5. 大数据和云计算技术周报(第27期)
  6. 下划线_在Python中的用途
  7. 基于开源CMDB系统快速实现一棵服务树
  8. Python-web验证码的实现
  9. 政务大数据系列7:政务大数据的部署结构
  10. Python将一个数逆序列放入列表中