• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
Free_rein
博客园    首页    新随笔    联系   管理    订阅  订阅

Java代码获取属性文件(.properties)中的value值

首先创建一个属性文件:application.properties 如下:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc\:mysql\://localhost\:3306/xxx
jdbc.username=root
jdbc.password=root
#hibernate settings
hibernate.show_sql=true
hibernate.format_sql=true

然后创建一个读取properties的类:PropertyReader.java

假设路径为:com.xxx.common\PropertyReader.java

View Code
package com.xxx.common;

import java.io.FileNotFoundException;  
import java.io.IOException;  
import java.io.InputStream;
import java.util.Properties;

public class PropertyReader {

    private Properties prop;  
    private String path;
    
    public PropertyReader(String path)  
    {  
        this.prop=new Properties();  
        this.path=path;  
          
        try {  
            InputStream in = PropertyReader.class.getResourceAsStream("application.properties");
            this.prop.load(in);
            System.out.println(prop.getProperty("jdbc.url").toString());
            in.close();  
        } catch (FileNotFoundException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
          
    }  
      
    public String getProperty(String key)  
    {  
        return prop.getProperty(key);  
    }  
      
    public void addProperty(String key,String value)  
    {  
         prop.put(key, value);  
    }  
}

很多人会纠结其中的路径问题,这里给出的是一种获取相对路径的方式

我们看这一行代码:

InputStream in = PropertyReader.class.getResourceAsStream("application.properties");

其中application.properties需要保存在PropertyReader.java这个类编译生成的PropertyReader.class所在的目录下面

如果路径是src这个目录下的话(src\com.xxx.common)

则路径应该是:

InputStream in = PropertyReader.class.getResourceAsStream("。。/。。/../application.properties");
posted @ 2013-04-14 14:50  Free_rein  阅读(995)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3