jai*_*jai 7 java jar properties
我们有一个应用程序的连接池组件(JAR文件).截至目前,应用程序连接详细信息与JAR文件(.properties文件中)捆绑在一起.
我们可以让它更通用吗?我们可以让客户端告诉属性文件详细信息(路径和文件名)并使用JAR来获取连接吗?
在客户端代码中有这样的东西是否有意义:
XyzConnection con = connectionIF.getConnection(uname, pwd);
Run Code Online (Sandbox Code Playgroud)
除此之外,客户端将指定(以某种方式???)具有要连接的URL,超时等的属性文件详细信息.
Ale*_*yak 16
最简单的方法是,使用-D开关在java命令行上定义系统属性.该系统属性可能包含属性文件的路径.
例如
java -cp ... -Dmy.app.properties=/path/to/my.app.properties my.package.App
Run Code Online (Sandbox Code Playgroud)
然后,在您的代码中,您可以执行(为简洁起见,未显示异常处理):
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
...
}
Run Code Online (Sandbox Code Playgroud)
http://www.javaworld.com/javaworld/javaqa/2003-08/01-qa-0808-property.html
有多种方法,上面的文章提供了更多细节
ClassLoader.getResourceAsStream ("some/pkg/resource.properties");
Class.getResourceAsStream ("/some/pkg/resource.properties");
ResourceBundle.getBundle ("some.pkg.resource");
Run Code Online (Sandbox Code Playgroud)
只需加载文件中的属性即可
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) {}
}
}
Run Code Online (Sandbox Code Playgroud)
请注意如何将编码明确指定为上面的UTF-8.如果您接受默认的ISO8859-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"));
Run Code Online (Sandbox Code Playgroud)