2010-08-11 108 views
5

我們爲我們的應用程序提供了連接池comeponent(jar文件)。 截至目前,應用程序連接詳細信息與jar文件(在.properties文件中)捆綁在一起。jar文件如何讀取外部屬性文件

我們可以使它更通用嗎?我們可以讓客戶端告訴屬性文件的詳細信息(包括路徑和文件名)並使用jar來獲取連接嗎?

是否有意義有在客戶端代碼是這樣的..

XyzConnection con = connectionIF.getConnection(uname, pwd); 

與此相伴,客戶端將指定(不知580)屬性文件有細節 - 網址連接,超時等等

回答

5

單從文件加載的屬性,像

Properties properties = new Properties(); 
InputStreamReader in = null; 
try { 
    in = new InputStreamReader(new FileInputStream("propertiesfilepathandname"), "UTF-8"); 
    properties.load(in); 
} finally { 
    if (null != in) { 
     try { 
      in.close(); 
     } catch (IOException ex) {} 
    } 
} 

注編碼是如何顯式指定爲UTF-8以上。如果您接受默認的ISO8859-1編碼,也可以忽略它,但請注意任何特殊字符。

13

最簡單的方法,使用-D開關在java命令行上定義系統屬性。 該系統屬性可能包含您的屬性文件的路徑。

E.g

java -cp ... -Dmy.app.properties=/path/to/my.app.properties my.package.App 

然後,在你的代碼,你可以做(​​沒有顯示爲簡潔的異常處理):

String propPath = System.getProperty("my.app.properties"); 

final Properties myProps; 

if (propPath != null) 
{ 
    final FileInputStream in = new FileInputStream(propPath); 

    try 
    { 
     myProps = Properties.load(in); 
    } 
    finally 
    { 
     in.close(); 
    } 
} 
else 
{ 
    // Do defaults initialization here or throw an exception telling 
    // that environment is not set 
    ... 
} 
0

最簡單的方法如下。它將從jar文件以外的cfg文件夾加載application.properties。

目錄結構

|-cfg<Folder>-->application.properties 
    |-somerunnable.jar 

代碼:

Properties mainProperties = new Properties(); 
    mainProperties.load(new FileInputStream("./cfg/application.properties")); 
    System.out.println(mainProperties.getProperty("error.message")); 
-1
public static String getPropertiesValue(String propValue) { 
     Properties props = new Properties(); 
     fileType = PCLLoaderLQIOrder.class.getClassLoader().getResourceAsStream(propFileName); 
     if (fileType != null) { 
      try { 
       props.load(fileType); 
      } catch (IOException e) { 
       logger.error(e); 
      } 
     } else { 
      try { 
       throw new FileNotFoundException("Property file" + propFileName + " not found in the class path"); 
      } catch (FileNotFoundException e) { 
       logger.error(e); 
      } 
     } 
     String propertiesValue = props.getProperty(propValue); 
     return propertiesValue; 
    } 

以上方法適用於我,只是你的屬性文件存放到哪裏運行jar目錄和地方提供的名字的propFileName,當你想要屬性的任何值只需撥打getPropertyValue("name")

+1

這是難以辨認的加載。 – 2017-09-06 12:56:02

1

這是我的解決方案。 首先尋找在啓動文件夾app.properties,如果不存在試圖從你的jar包

File external = new File("app.properties"); if (external.exists()) properties.load(new FileInputStream(external)); else properties.load(Main.class.getClassLoader().getResourceAsStream("app.properties"));