android的文件存储

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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

留白的云

感谢鼓励。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值