Java的配置文件.properties文件和xml文件。

一、properties文件
.properties配置文件是什么?
答:Properties文件是java中很常用的一种配置文件,文件后缀为“.properties”,属文本文件,文件的内容格式是“键=值”的格式,可以用“#”

作为注释,java编程中用到的地方很多,运用配置文件,可以便于java深层次的解耦。
例如java应用通过JDBC连接数据库时,可以把数据库的配置写在配置文件 jdbc.properties:
driver=com.mysql.jdbc.Driver 
jdbcUrl=jdbc:mysql://localhost:3306/user 
user=root 
password=123456

二、Properties类
java中提供了配置文件的操作类Properties类(java.util.Properties):

读取properties文件的通用方法:根据键得到value
/**
     * 读取config.properties文件中的内容,放到Properties类中
     * @param filePath 文件路径
     * @param key 配置文件中的key
     * @return 返回key对应的value
     */
    public static String readConfigFiles(String filePath,String key) {
        Properties prop = new Properties();
        try{
            InputStream inputStream = new FileInputStream(filePath);
            prop.load(inputStream);
            inputStream.close();
            return prop.getProperty(key);
        }catch (Exception e) {
            e.printStackTrace();
            System.out.println("未找到相关配置文件");
            return null;
        }
    }

把配置文件以键值对的形式存放到Map中:
/**
     * 把.properties文件中的键值对存放在Map中
     * @param inputStream 配置文件(inputstream形式传入)
     * @return 返回Map
     */
    public Map<String, String> convertPropertityFileToMap(InputStream inputStream) {
        try {
            Properties prop = new Properties();
            Map<String, String> map = new HashMap<String, String>();
            if (inputStream != null) {
                prop.load(inputStream);
                Enumeration keyNames = prop.propertyNames();
                while (keyNames.hasMoreElements()) {
                    String key = (String) keyNames.nextElement();
                    String value = prop.getProperty(key);
                    map.put(key, value);
                }
                return map;
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }





在XML配置文件中使用properties文件的键值作为变量化参数

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值