2012年4月25日 星期三

使用properties檔將字串匯入class


在使用下列程式碼之前需將properties檔案放至與class相同目錄下(通常為/src)
正常而言,大多不需要再加入getConfig()此method,而直接使用props.getProperty("String");
但使用在需匯入大量程式碼時可減少程式碼,程式中註解部分為將檔案位置指派為絕對位置亦可獲得,但若是你的專案需要匯出至其它地方佈署(如webserver),則new FileInputStream不建議使用,而改為使用getResourceAsStream(),且記得getClassLoader();
正常來說對於loadProperties() methed而言,不需要使用static,特別是你的專案需要匯出的時候,以節省記憶體

private  Properties props;

  private  void loadProperties() throws FileNotFoundException, IOException {
       props = new Properties();
       try{
      InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("VaDAO.properties");
         props.load(inputStream);  
      //props.load(new FileInputStream("C:/temp/datasource.properties"));
       
       }catch (FileNotFoundException e) {
         e.printStackTrace();
       } catch (IOException e) {
            e.printStackTrace();
       }
       
  }

  private  String getConfig(String key) {
      return props.getProperty(key);
  }

---------------------------------------------------------------------------------------
使用上面method來匯入我們的class檔
private void test(){


loadProperties();

String WLInitContextFactory = getConfig("weblogic.jndi.WLInitialContextFactory");
String provider_url = getConfig("PROVIDER_URL");
String ds_jndi_name = getConfig("VA_DS_JNDI_NAME");

System.out.print("WLInitContextFactory ---->"+ WLInitContextFactory  );
System.out.print("provider_url -------->"+provider_url );
System.out.print("ds_jndi_name --------->"+ds_jndi_name );

}

我的properties檔名稱為VaDAO.properties
內容為
weblogic.jndi.WLInitialContextFactory=weblogic.jndi.WLInitialContextFactory
PROVIDER_URL=t3://192.168.11.24:8080
VA_DS_JNDI_NAME=DS_VA


若method正常執行則會秀出
WLInitContextFactory ---->weblogic.jndi.WLInitialContextFactory
provider_url -------->t3://192.168.11.24:8080
ds_jndi_name --------->DS_VA

沒有留言:

張貼留言