《第一行代码-Android》学习笔记(九)

1.瞬时数据:指那些存储在内存当中,有可能因为程序关闭或其他导致内存被回收而丢失的数据。

 

2.数据持久化技术简介:是指将那些内存中的瞬时数据保存到存储设备中,保证及时收集或者电脑关机,这些数据仍然不会丢失。

 

3.android三种数据持久化方法:本地存储、SharedPreference存储以及数据库存储。

 

4.文件存储:文件的操作模式在4.2版本之前一共有4种:

a) MODE_PRIVATE:值当指定同样文件名的时候,所写入的内容将会覆盖原文件。

b) MODE_APPEND:指如果该文件已经存在那么就往文件里追加内容,不存在就创建新文件。

c) MODE_WORLD_READABLE:只可读(4.2版本中废除)

d) MODE_WORLD_WRITEABLE:可写(4.2版本中废除)

 

5.从文件中读取数据:

a) 用到了context的两个方法:

this.openFileInput("data.txt")   ---

this.openFileOutput("data.txt", Context.MODE_PRIVATE);

---

并且学到了EditText可以设置光标定位的位置:

contentEt.setSelection(content.length());

 

b) 具体代码

i. 

private void load()

    {

        FileInputStream fileInputStream = null;

        BufferedReader reader = null;

        StringBuilder content = new StringBuilder();

        try

        {

            fileInputStream = this.openFileInput("data.txt");

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

            

            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();

                }

            }

        }

        if (!TextUtils.isEmpty(content))

        {

            contentEt.setText(content);

            contentEt.setSelection(content.length());

        }

  }

ii. 

 protected void onSave(String content)

    {

        FileOutputStream fileOutputStream = null;

        BufferedWriter bufferedWriter = null;

        try

        {

            fileOutputStream = this.openFileOutput("data.txt", Context.MODE_PRIVATE);

            bufferedWriter = new BufferedWriter(new OutputStreamWriter(fileOutputStream));

            bufferedWriter.write(content);

        }

        catch (FileNotFoundException e)

        {

            e.printStackTrace();

        }

        catch (Exception e)

        {

            e.printStackTrace();

        }

        finally

        {

            if (bufferedWriter != null)

            {

                try

                {

                    bufferedWriter.close();

                }

                catch (IOException e)

                {

                    e.printStackTrace();

                }

            }

        }

                }

6.android中判断字符串非空最好使用api中的工具方法:

TextUtils.isEmpty(content)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值