Android 中的数据存储----文件存储

一 文件存储

文件存储是原封不动的存储到文件中。

数据类型:简单的文本数据、二进制数据。

存储位置:/data/data/项目包名/files/

应用场景:不知道

 

核心技术:

1 Context 提供了 openFileInput() openFileOutput() 获得流对象

2利用流进行读写,不允许指定存储位置,系统自动会找到位置。

 

示例:

write(String fileName, String data)   将数据存储到文件中

String  read(String fileName)      从文件中读取数据

------------------------begin--------------------------

public void write(String fileName, String data)

{

         FileOutputStreamout = null;

         BufferedWriterwriter = null;

         try

         {

                  out = openFileOutput(fileName, Context.MODE_PRIVATE); //还有MODE_APPEND, 表示覆盖

                  writer = new BufferedWriter(newOutputStreamWriter(out));

                  writer.write(data);

          }

          catch(IOExceptione){e.printStackTrace();}

          finally{ if(writer!=null)try{writer.close();}catch(IOExceptione){e.printStackTrace();}}

}

 

public String read(String fileName)

{

         FileInputStreamin = null;

         BufferedReaderreader = null;

         StringBuildertempSb = new StringBuilder();

         try

         {

                 in = openFileInput(fileName);

                 reader = new BufferedReader (new InputStreamReader(in));

                 Stringline = “”;

                 while((line = reader.readLine()) != null )

                 {

                         tempSb.append(line);

                 }

         }

         catch(IOExceptione){e.printStackTrace();}

         finally{ if(reader!=null)try{reader.close();}catch(IOExceptione){e.printStackTrace();}}

         returntempSb.toString();

}

------------------------end----------------------------

要去查看是否存储成功,可以在视图DDMSFile Explore,找到文件,点击向左箭头的按钮,导出到电脑,用记事本打开查看。

 

要用代码得到存储路径,可以使用如下方式:

String file_path = getFilesDir().getPath();              // file_path=/data/data/项目包名/files

String cache_path = getCacheDir().getPath();      // cache_path=/data/data/项目包名/cache

 

本文参考《第一行代码》

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值