Fork me on GitHub

properties配置文件

java.util.Properties基础
读取:
Properties prop = new Properties();//属性集合对象    
FileInputStream fis = new FileInputStream("prop.properties");//属性文件流    
prop.load(fis);//将属性文件流装载到Properties对象中
prop.getProperty("key");   //根据指定key获取properties中对应的值
prop.getProperty("key","value");   //根据指定key获取properties中对应的值,如果这个key未定义,则返回默认值vlaue

写入

Properties prop = new Properties();//属性集合对象 
prop.setProperty("key1", "value1"); //修改key1的属性值 
prop.setProperty("key2", "value2"); //添加一个新的属性key2
//文件输出流 
FileOutputStream fos = new FileOutputStream("prop.properties"); 
//将Properties集合保存到流中 
prop.store(fos, "remark"); 
fos.close();//关闭流 

properties配置文件util类

    private String fileName = null;
    private String propKey = null;
    private URL url = null;
    Properties properties = new Properties();
    
    /**
     * 根据url实例化properties
     * @param url
     * @throws URISyntaxException
     * @throws IOException
     */
    public PropUtil(URL url) throws URISyntaxException, IOException {
        this.url = url;
        File file =new File(url.toURI());
        if (file!=null) {
            FileInputStream fis = new FileInputStream(file);
            properties.load(fis);
        }
    }

    /**
     * 根据文件全路径实例化properties
     * @param fileName
     */
    public PropUtil(String fileName) {
        this.fileName = fileName;
        try {
            if (fileName!=null&&!fileName.isEmpty()) {
                InputStream is = new FileInputStream(fileName);
                properties.load(is);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 根据properties的key值获取value
     * @param key
     * @return
     */
    public String getPro(String key) {
        String value = properties.getProperty(key);    
        return value;
    }

源码

posted @ 2017-10-30 11:17  秋夜雨巷  阅读(742)  评论(0编辑  收藏  举报