java配置文件-properties

用法:

1. getProperty ( String key),用指定的键在此属性列表中搜索属性。也就是通过参数 key ,得到 key 所对应的 value。

2. load ( InputStream inStream),从输入流中读取属性列表(键和元素对)。通过对指定的文件(比如说上面的 test.properties 文件)进行装载来获取该文件中的所有键 - 值对。以供 getProperty ( String key) 来搜索。

3. setProperty ( String key, String value) ,调用 Hashtable 的方法 put 。他通过调用基类的put方法来设置 键 - 值对。

4. store ( OutputStream out, String comments),以适合使用 load 方法加载到 Properties 表中的格式,将此 Properties 表中的属性列表(键和元素对)写入输出流。与 load 方法相反,该方法将键 - 值对写入到指定的文件中去。

5. clear (),清除所有装载的 键 - 值对。该方法在基类中提供。

获取配置文件:

        Properties properties = new Properties();
        try {
            properties.load(new InputStreamReader(PropertiesUtil.class.getClassLoader().getResourceAsStream(fileName),"UTF-8"));
        } catch (IOException e) {
            e.printStackTrace();
        }

读取配置文件内容:

    public static String getProperty(String key){
        String value = props.getProperty(key.trim()); //获取关键字名字
        if (StringUtils.isBlank(value)){
            return null;
        }
        return value.trim();

//        public String getProperty(String key) {
//            Object oval = super.get(key);
//            String sval = (oval instanceof String) ? (String)oval : null;
//            return ((sval == null) && (defaults != null)) ? defaults.getProperty(key) : sval;
//        }
    }

使用(得到配置文件到IP地址):

//    public static void main(String[] args) {
//        String ftpIp = PropertiesUtil.getProperty("ftp.server.ip");
//        System.out.println(ftpIp);
//    }
发布了37 篇原创文章 · 获赞 4 · 访问量 6835

猜你喜欢

转载自blog.csdn.net/m0_37918421/article/details/88956140