java配置文件

普通java工程

比如配置文件名为a.properties
所在的类名为b

所在包名为c,若配置文件在src下则与c无关,否则加载时必须加上c

Properties props = new Properties(); //对应配置文件

//加载配置文件

方式一:
                props.load(b.class.getResourceAsStream("a.properties"));
方式二:

                props.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("c/a.properties"));

方式三:

                Locale locale1 = new Locale("zh", "CN"); 
ResourceBundle r = ResourceBundle.getBundle("a/Config",locale1);
String str = r.getString("user");//user为key
System.out.println(str);

方式一,二都用props.getProperty("key的名字")来得到value;

//读取所有内容
for(Entry<Object ,Object> entry:props.entrySet ){
        Ststem.out.println(entry.getKey() + "--" entry.getValue());
}

javaWeb工程

            比如在src下有个配置文件config.properties,那么在servlet中读取的时候,可以分为相对路径与和绝对路径(此处纯属测试,真正项目中应该用相对路径)

            相对路径:   
                使用getResourceAsStream()方法                  
ServletContext con = this.getServletContext();
InputStream in = con.getResourceAsStream("/WEB-INF/classes/config.properties");
Properties prop = new Properties();
prop.load(in);
System.out.println(prop.get("username"));//直接在控制台打印
            绝对路径:
                 使用new FileInputStream();
如果使用绝对路径,可以使用getRealPath方法, 但方法的参数需要是相对路径,否则得出的绝对路径不对,如果只用配置文件名需要类加载器定位到classes目录
ServletContext con = this.getServletContext();
String realPath1 = con.getRealPath("config.properties");
String realPath2 = con.getRealPath("/WEB-INF/classes/config.properties");
System.out.println(realPath1);//---------E:/apache-tomcat-8.5.31/webapps/HelloServlet/config.properties
System.out.println(realPath2);//---------E:/apache-tomcat-8.5.31/webapps/HelloServlet/WEB-INF/classes/config.properties
//InputStream in = new FileInputStream(realPath1);---------------------------false
InputStream in   = new FileInputStream(realPath2);//---------------------------true
//InputStream in = con.getResourceAsStream(realPath2);-------false
Properties prop = new Properties();
prop.load(in);
System.out.println(prop.get("username"));//直接在控制台打印


借助类加载器(茅塞顿开)



        
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值