1. 程式人生 > >java 讀取src目錄下配置檔案

java 讀取src目錄下配置檔案

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);