zoukankan      html  css  js  c++  java
  • android数据存储方式(三)Files

         平时的我们如果想要保信息,一般的做法就是记在本子上,然后在使用的时候从本子中拿出来。android保存数据的方式也可以像是这样先将数据保存在文件中,然后再从文件中读取。采取这种方式,我们可以在程序间共享信息,但默认下,android的文件是私有的,要想共享,需要权限。

          例子就用上一篇文章中的CheckBox,用文件的方式保存点击状态(例子的详情请看:http://www.cnblogs.com/wenjiang/archive/2013/06/02/3114017.html)

          直接就是代码:

    private boolean isCheck;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            CheckBox checkbox = (CheckBox) this.findViewById(R.id.checkbox);
            getProperties();
            checkbox.setChecked(isCheck);
            checkbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
    
                @Override
                public void onCheckedChanged(CompoundButton buttonView,
                        boolean isChecked) {
                    isCheck = isChecked;
                }
            });
        }
    
        private boolean saveProperties() {
            Properties properties = new Properties();
            properties.put("info", String.valueOf(isCheck));
            try {
                FileOutputStream out = this.openFileOutput("info.cfg",
                        Context.MODE_WORLD_WRITEABLE);
                properties.store(out, "");
            } catch (FileNotFoundException e) {
                return false;
            } catch (IOException e) {
                return false;
            }
            return true;
        }
    
        private void getProperties() {
            Properties properties = new Properties();
            try {
                FileInputStream in = this.openFileInput("info.cfg");
                properties.load(in);
            } catch (FileNotFoundException e) {
                return;
            } catch (IOException e) {
                return;
            }
            isCheck = Boolean.valueOf(properties.getProperty("info").toString());
        }
    
        public boolean onKeyDown(int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                saveProperties();
                this.finish();
                return true;
            }
            return super.onKeyDown(keyCode, event);
        }

          由于涉及到I/O,所以异常处理机制必要的。流程是这样的:我们先使用put()将数据打包,同样是键值对,然后通过store()将数据保存在指定的文件中,如果没有,就创建一个,最后再通过load()读取文件内容。load()读取文件内容并不直接取出数据,它是将文件内容放在properties中,所以我们需要通过get()方法取出相应的数据。

          内容确实非常简单,权当记录吧。

  • 相关阅读:
    为什么要使用智能指针?
    C++如何定义一个函数指针
    Python三个处理excel表格的库
    Python的一个mysql实例
    Python利用xlutils统计excel表格数据
    PHP连接数据库的方式
    利用xlutils第三方库复制excel模板
    Python自动化办公第三方库xlwt
    Python之excel第三方库xlrd和xlwt
    Python生成器
  • 原文地址:https://www.cnblogs.com/wenjiang/p/3114312.html
Copyright © 2011-2022 走看看