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. 浅谈Java中Collections.sort对List排序的两种方法
  2. NPM 和webpack 的基础使用
  3. Python list sort方法的具体使用
  4. 【阿里云镜像】使用阿里巴巴DNS镜像源——DNS配置教程
  5. python list.sort()根据多个关键字排序的方法实现
  6. android上一些方法的区别和用法的注意事项
  7. 读取android手机流量信息
  8. android 使用html5作布局文件: webview跟javascript交互
  9. android实现字体闪烁动画的方法

随机推荐

  1. Android--登录界面(demo)
  2. android http请求
  3. Best Android(安卓)Books: My Top 5 Choi
  4. 【Android】串口通信
  5. Android(安卓)文件储存
  6. android 访问SQLite
  7. android calendar的使用
  8. Android(安卓)Retrofit下载文件
  9. Android全局捕获异常
  10. android TextView文字透明度和背景透明度