zoukankan      html  css  js  c++  java
  • Android下使用Properties文件保存程序设置

    原文:http://jerrysun.blog.51cto.com/745955/804789

    废话不说,直接上代码。
        读取.properties文件中的配置: 

     

    String strValue = ""; 
    Properties props = new Properties(); 
    try { 
        props.load(context.openFileInput("config.properties")); 
        strValue = props.getProperty (keyName); 
        System.out.println(keyName + " "+strValue); 
    } 
    catch (FileNotFoundException e) { 
        Log.e(LOG_TAG, "config.properties Not Found Exception",e); 
    } 
    catch (IOException e) { 
        Log.e(LOG_TAG, "config.properties IO Exception",e); 
    } 

        相信上面这段代码大部分朋友都能看懂,所以就不做过多的解释了。

        向.properties文件中写入配置:

      

    Properties props = new Properties(); 
    try { 
        props.load(context.openFileInput("config.properties")); 
        OutputStream out = context.openFileOutput("config.properties",Context.MODE_PRIVATE); 
        Enumeration<?> e = props.propertyNames(); 
        if(e.hasMoreElements()){ 
            while (e.hasMoreElements()) { 
                String s = (String) e.nextElement(); 
                if (!s.equals(keyName)) { 
                    props.setProperty(s, props.getProperty(s)); 
                } 
            } 
        } 
        props.setProperty(keyName, keyValue); 
        props.store(out, null); 
        String value = props.getProperty(keyName); 
        System.out.println(keyName + " "+value); 
    } 
    catch (FileNotFoundException e) { 
        Log.e(LOG_TAG, "config.properties Not Found Exception",e); 
    } 
    catch (IOException e) { 
        Log.e(LOG_TAG, "config.properties IO Exception",e); 
    } 
    

      

        上面这段代码,跟读取的代码相比,多了一个if判断以及一个while循环。主要是因为Context.Mode造成的。因为我的工程涉及到多个配置信息。所以只能是先将所有的配置信息读取出来,然后在写入配置文件中。
        Context.Mode的含义如下:
        1.MODE_PRIVATE:为默认操作模式,代表该文件是私有数据,只能被应用本身访问,在该模式下,写入的内容会覆盖原文件的内容。
        2.MODE_APPEND:代表该文件是私有数据,只能被应用本身访问,该模式会检查文件是否存在,存在就往文件追加内容,否则就创建新文件。
        3.MODE_WORLD_READABLE:表示当前文件可以被其他应用读取。
        4.MODE_WORLD_WRITEABLE:表示当前文件可以被其他应用写入。

        注:.properties文件放置的路径为/data/data/packagename/files

  • 相关阅读:
    java线程池,工作窃取算法
    java线程池,阿里为什么不允许使用Executors?
    CMakeLists 的使用,大型工程使用cmake 的构件过程
    ieee文献免费下载办法
    欧式距离、标准化欧式距离、马氏距离、余弦距离
    sliding window:"Marginalization","Schur complement","First estimate jacobin"
    机器学习中的线性代数之矩阵求导
    opencv中滤波方法学习
    opencv关于Mat类中的Scalar()---颜色赋值
    C/C++预处理指令#define,#ifdef,#ifndef,#endif…
  • 原文地址:https://www.cnblogs.com/yjpjy/p/5407251.html
Copyright © 2011-2022 走看看