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

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

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

    1. String strValue = ""
    2. Properties props = new Properties(); 
    3. try { 
    4.     props.load(context.openFileInput("config.properties")); 
    5.     strValue = props.getProperty (keyName); 
    6.     System.out.println(keyName + " "+strValue); 
    7. catch (FileNotFoundException e) { 
    8.     Log.e(LOG_TAG, "config.properties Not Found Exception",e); 
    9. catch (IOException e) { 
    10.     Log.e(LOG_TAG, "config.properties IO Exception",e); 

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

        向.properties文件中写入配置:

    1. Properties props = new Properties(); 
    2. try { 
    3.     props.load(context.openFileInput("config.properties")); 
    4.     OutputStream out = context.openFileOutput("config.properties",Context.MODE_PRIVATE); 
    5.     Enumeration<?> e = props.propertyNames(); 
    6.     if(e.hasMoreElements()){ 
    7.         while (e.hasMoreElements()) { 
    8.             String s = (String) e.nextElement(); 
    9.             if (!s.equals(keyName)) { 
    10.                 props.setProperty(s, props.getProperty(s)); 
    11.             } 
    12.         } 
    13.     } 
    14.     props.setProperty(keyName, keyValue); 
    15.     props.store(out, null); 
    16.     String value = props.getProperty(keyName); 
    17.     System.out.println(keyName + " "+value); 
    18. catch (FileNotFoundException e) { 
    19.     Log.e(LOG_TAG, "config.properties Not Found Exception",e); 
    20. catch (IOException e) { 
    21.     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

  • 相关阅读:
    [转]How do I use variables in Oracle SQL Developer?
    [转]一张图理解prototype、proto和constructor的三角关系
    [转]ASP.NET Web API系列教程(目录)
    [转]解读ASP.NET 5 & MVC6系列(7):依赖注入
    [转]什么?你还不会写JQuery 插件
    [书目20170314]理解未来的7个原则
    java List.subList方法中的超级大陷阱
    MyBatis动态传入表名,字段名参数的解决办法---statementType用法
    lvs+keepalived和haproxy+heartbeat区别
    Nginx/LVS/HAProxy负载均衡软件的优缺点详解
  • 原文地址:https://www.cnblogs.com/SummerRain/p/3266546.html
Copyright © 2011-2022 走看看