android 持久化技术(一)文件存储

文件存储-----将简单数据存到文本中

如何存储数据到文本

 public void save(String data){
        /*
        * Context类提供了openFileOutput()方法用于将数据存储到指定文件中
        * 该方法由两个参数
        * 第一个参数:新建(自定义)的文本文件名
        * 第二个参数:文件的操作模式,操作模式有两种
        *             第一种操作模式:MODE_PRIVARE(内置常量,直接用),该模式为默认的模式,当填写的文件名已存在时,会会进行内容覆盖
        *             第二种操作模式:MODE_APPEND  若填写文件名已存在,则内容追加,否则新建填入
        * openFileOutput()会返回一个FileOutputStream实例
        * 而OutputStreamWriter的实例由FileOutputStream实例作为形参进行构建
        * BufferedWriter实例由OutputStreamWriter实例作为形参进行构建
        * 最终由BufferedWriter实例调用write()方法写入数据*/
        FileOutputStream out=null;
        BufferedWriter writer=null;
        try {
            out=openFileOutput("data", Context.MODE_PRIVATE);
            writer=new BufferedWriter(new OutputStreamWriter(out));
            writer.write(data);
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                if(writer != null)
                    writer.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

        }
    }
这里的output的意思是,相对本程序,将内容写到程序外的文本中,就是内容输出。接下来的input也是相同的道理。

既然内容存好了,怎么去查看新建好的文本和保存好的内容呢?

看到Android Studio导航栏中的tools,点击选中Android,再从弹出的列表中选中Android Device Monitor,点击后反应会有点慢,等下就好,如图所示再选中File Explorer,找到/data/data/com.example.XX(自己的项目名)/files/ 然后就可以看到自己保存的文本文件了,那怎么查看呢?导出到电脑桌面,选择文本打开方式就OK

如何读取文本数据到程序

过程原理与存储一样,非常容易理解

 public String load(){
        FileInputStream in=null;
        BufferedReader reader = null;
        StringBuilder content=new StringBuilder();
        try {
            in=openFileInput("data");
            reader= new BufferedReader(new InputStreamReader(in));
            String line="";
            while ((line=reader.readLine())!=null){
                content.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(reader != null){
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return content.toString();
    }
}

一直非常喜欢的一句话,来自郭霖《第一行代码》,做自己喜欢做的事,永远也不会迟!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值