java 读取src目录下配置文件

来源:互联网 发布:nginx 前后端分离 编辑:程序博客网 时间:2024/06/05 03:05

1.使用java.util.Properties类
1.1 getResourceAsStream()有时候不一定读的出来

Properties prop=new Properties();InputStream in=new BufferedInputStream(this.getClass().getClassLoader().getResourceAsStream("/jdbc.properties"));prop.load(in);in.close();

1.2 getResource().getPath()就一定可以读取得到

Properties prop=new Properties();String path=LoginAction.class.getClassLoader().getResource("//").getPath()+"jdbc.properties";prop.load(new BufferedInputStream (new FileInputStream(path)));

2.通过java.util.ResourceBundle类来读取,这种方式比使用Properties要方便一些。
2.1、通过ResourceBundle.getBundle()静态方法来获取(ResourceBundle是一个抽象类),这种方式来获取properties属性文件不需要加.properties后缀名,只需要文件名即可。
[java] view plaincopy

ResourceBundle resource = ResourceBundle.getBundle("com/mmq/test");//test为属性文件名,放在包com.mmq下,如果是放在src下,直接用test即可  String key = resource.getString("username");  

2.2、从InputStream中读取,获取InputStream的方法和上面一样,不再赘述。
[java] view plaincopy

ResourceBundle resource = new PropertyResourceBundle(inStream);  
0 0
原创粉丝点击