Java JAR 文件如何读取外部属性文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3457918/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 00:57:17  来源:igfitidea点击:

How a JAR file can read an external properties file

javapropertiesjar

提问by jai

We have a connection pooling component (JAR file) for one of our application. As of now the application connection details are bundled with-in the JAR file (in .propertiesfile).

我们有一个用于我们的应用程序的连接池组件(JAR 文件)。截至目前,应用程序连接详细信息已捆绑在 JAR 文件中(.properties文件中)。

Can we make it more generic? Can we have the client tell the properties file details (both the path and the file name) and use the JAR to get the connection?

我们可以让它更通用吗?我们可以让客户端告诉属性文件的详细信息(路径和文件名)并使用 JAR 获取连接吗?

Does it make sense to have something like this in the client code:

在客户端代码中包含这样的内容是否有意义:

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

Along with this, the client will specify (somehow???) the properties file details that has the URLs to connect, timeout etc.

与此同时,客户端将指定(以某种方式???)具有要连接的 URL、超时等的属性文件详细信息。

采纳答案by Aaron Saunders

http://www.javaworld.com/javaworld/javaqa/2003-08/01-qa-0808-property.html

http://www.javaworld.com/javaworld/javaqa/2003-08/01-qa-0808-property.html

multiple approaches are available, the article above provides more details

有多种方法可用,上面的文章提供了更多详细信息

 ClassLoader.getResourceAsStream ("some/pkg/resource.properties");
 Class.getResourceAsStream ("/some/pkg/resource.properties");
 ResourceBundle.getBundle ("some.pkg.resource");

回答by Joonas Pulakka

Just load the properties from file, something like

只需从文件加载属性,就像

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) {}
     }
}

Note how the encoding is explicitly specified as UTF-8 above. It could also be left out if you accept the default ISO8859-1 encoding, but beware with any special characters then.

请注意上面的编码是如何明确指定为 UTF-8 的。如果您接受默认的 ISO8859-1 编码,也可以省略它,但要注意任何特殊字符。

回答by Alexander Pogrebnyak

Simplest way, use the -D switch to define a system property on a java command line. That system property may contain a path to your properties file.

最简单的方法,使用 -D 开关在 java 命令行上定义系统属性。该系统属性可能包含属性文件的路径。

E.g

例如

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

Then, in your code you can do ( exception handling is not shown for brevity ):

然后,在您的代码中,您可以执行以下操作(为简洁起见,未显示异常处理):

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
     ...
}

回答by Pratiyush Kumar Singh

Simplest way is below. It will load application.properties from cfg folder outside of the jar file.

最简单的方法如下。它将从 jar 文件外部的 cfg 文件夹加载 application.properties。

Directory Structure

目录结构

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

Code:

代码:

    Properties mainProperties = new Properties();
    mainProperties.load(new FileInputStream("./cfg/application.properties"));
    System.out.println(mainProperties.getProperty("error.message"));

回答by Naresh Kumar

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

above methods works for me, just store your property file into directory from where to run your jar and provide that name in place of propFileName, when you want any value from property just call getPropertyValue("name").

上述方法对我有用,只需将您的属性文件存储到运行 jar 的目录中,并提供该名称代替 propFileName,当您想要来自属性的任何值时,只需调用getPropertyValue("name").

回答by tarn

This is my solution. First looking for app.propertiesin startup folder, if does not exists try to load from your JAR package:

这是我的解决方案。首先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"));

回答by David Becerra Montellano

In netbeans I needed to load application.properties from conf/folder outside of the jar file.

在 netbeans 中,我需要从conf/jar 文件之外的文件夹加载 application.properties 。

Therefore I wrote :

因此我写道:

public static String getProperty(String FileName, String Prop)
{   

    try {  
        FIS = new FileInputStream( "./../conf/"+FileName);
        Properties properties;
        (properties = new Properties()).load(FIS);          

        for(Enumeration propKeys = properties.propertyNames();
                propKeys.hasMoreElements();){
            String tmpKey = (String) propKeys.nextElement();
            String tmpValue = properties.getProperty(tmpKey);                   

            tmpValue = tmpValue.trim();
            if (tmpKey.equals(Prop)){
                //System.out.println(tmpKey +"="+tmpValue);
                properties.put(tmpKey, tmpValue);
                Value = properties.getProperty(Prop);
                break;
            }

        }

        if (Value==null){
            throw new Exception("La Propiedad : "+Prop+" no Se encuentra en el Archivo de Configuracion");
        } 

    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return Value;

}

For Eclipse apply the following:

对于 Eclipse,应用以下内容:

FIS = new FileInputStream( "../conf/"+FileName);