美文网首页
Properties的使用

Properties的使用

作者: 梦沉薇露 | 来源:发表于2017-06-21 14:20 被阅读4次

java 和android Properties的应用,请看main方法


public class PropertiesUtils {

    //根据Key读取Value
    public static String GetValueByKey(String filePath, String key) {
        Properties pps = new Properties();
        try {
            InputStream in = new BufferedInputStream(new FileInputStream(filePath));
            pps.load(in);
            String value = pps.getProperty(key);
            System.out.println(key + " = " + value);
            return value;

        }catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
        catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    //读取Properties的全部信息
    public static void GetAllProperties(String filePath) throws IOException {

        Properties pps = new Properties();
        InputStream in = new BufferedInputStream(new FileInputStream(filePath));
        pps.load(in);
        Enumeration en = pps.propertyNames(); //得到配置文件的名字

        while(en.hasMoreElements()) {
            String strKey = (String) en.nextElement();
            String strValue = pps.getProperty(strKey);
            System.out.println(strKey + "=" + strValue);
        }

    }

    //写入Properties信息
    public static void WriteProperties (String filePath, String pKey, String pValue) throws IOException {
        //props.load(context.openFileInput("config.properties"));// 安卓用的
        //OutputStream out = context.openFileOutput("config.properties",Context.MODE_PRIVATE);//安卓用的
        Properties pps = new Properties();
        InputStream in = new FileInputStream(filePath);
        pps.load(in);
        OutputStream out = new FileOutputStream(filePath);
        //下面这段为安卓多出来的。主要是因为Context.Mode造成的。
        Enumeration<?> e = pps.propertyNames();
        if(e.hasMoreElements()){
            while (e.hasMoreElements()) {
                String s = (String) e.nextElement();
                if (!s.equals(pKey)) {
                    pps.setProperty(s, pps.getProperty(s));
                }
            }
        }
        //上面这段为安卓多出来的。主要是因为Context.Mode造成的。
        pps.setProperty(pKey, pValue);
        pps.store(out, "Update " + pKey + " name");
    }

    public static void main(String [] args) throws IOException{
        //WriteProperties("Test.properties","ttt", "333");
        //GetValueByKey("Test.properties","Height");
        GetAllProperties("Test.properties");
    }

}

相关文章

网友评论

      本文标题:Properties的使用

      本文链接:https://www.haomeiwen.com/subject/kjttcxtx.html