2010-08-11 105 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"));