Java加载配置文件的方式

1.通过文件流来加载

1 InputStream in=  new FileInputStream("sample.properties");     
2 Properties properties = new Properties();
3 properties .load(in);

这种方式采用相对路径的方式加载,对于不同的系统、不同的运行环境不一定全都能正确加载

2.采用ClassLoader的getResourceAsStream方式进行加载

1 InputStream in = PropertiesTest.class.getClassLoader().getResourceAsStream("sample.properties");  
2 Properties properties = new Properties();
3 properties .load(in);

对于这种方式,getClassLoader()的默认位置是classes文件夹,但是如果类加载是委托机制,将有可能加载不成功

3.采用Class的getResourceAsStream方式进行加载

1 InputStream in = PropertiesTest.class.getResourceAsStream("sample.properties");  
2 Properties properties = new Properties();
3 properties .load(in);

对于这种方式,默认加载位置是class文件对应的位置

 

此外通过

1.PropertiesTest.class.getResource("sample.properties").getPath();

2.PropertiesTest.class.getClassLoader().getResource("sample.properties").getPath();

两种方式都可以获取文件的相对路径

posted on 2014-05-06 15:52  暮风吹雪  阅读(297)  评论(0编辑  收藏  举报

导航