简体   繁体   English

如何使用带有属性文件的Eclipse“导出为jar选项”来构建jar

[英]How to build jar using Eclipse “Export as jar option” with a properties file

public xFbConfigReader()
{

    //props = new Properties();
    propsdatabase = new Properties();

    try 
    {
        // load a properties file
        InputStream dbin = getClass().getResourceAsStream("/properties/database.properties");


        propsdatabase.load(dbin);

    } 
    catch (IOException ex) 
    {
        ex.printStackTrace();
    }

}

I keep My properties File named 'Database.properties' in a folder where the project is named 'Properties'. 我将名为“ Database.properties”的属性文件保存在项目名为“属性”的文件夹中。

When I do a Export as jar in Eclipse . 当我在Eclipse中执行Export as jar时。 The Properties Folder is visible. “属性”文件夹可见。

您可以看到属性文件夹

But When I run the program it shows that there is a NUll point exception in dbin. 但是,当我运行程序时,它表明dbin中存在NUll点异常。

So which means I require the proper way to form a jar in Eclipse .Kindly suggest. 所以这意味着我需要在Eclipse中形成jar的正确方法。

The better solution while handling properties file would be reading 处理属性文件时更好的解决方案是读取

static Properties databaseproperties= new Properties();
    static {
        try {
            connectionProps.load(YourClassName.class.getClassLoader()
                    .getResourceAsStream("databaseproperties.properties"));
        } catch (Exception e) {
            System.out.println("Exception is " + e.getMessage());
        }
    }

This is better approch because 这是更好的方法,因为

  • we can move our properties file to someother folder. 我们可以将属性文件移动到其他文件夹。
  • And infact we can keep properties folder out side of jar. 实际上,我们可以将Properties文件夹放在jar的外面。 say you can create a folder called Configuration where you can include all the properties files. 例如,您可以创建一个名为Configuration的文件夹,其中可以包含所有属性文件。 As it is out side of jar you can change the properties file when ever is required. 由于它不在jar的外部,因此您可以在需要时更改属性文件。
  • For change in properties file no need to unjar it. 对于属性文件的更改,无需将其解压缩。

(OR) simply you can make this change no need to think about directory structure (OR)只需进行更改即可,无需考虑目录结构

  1. Step 1: Move properties file to SRC 步骤1:将属性文件移动到SRC
  2. step 2: change this line as follows 步骤2:如下更改此行

    InputStream dbin = getClass().getResourceAsStream("/database.properties"); InputStream dbin = getClass()。getResourceAsStream(“ / database.properties”);

This is not much different from previous code as it is anyway stays inside the JAR file. 这与以前的代码没有太大区别,因为它始终保留在JAR文件中。

you are getting null pointer exception because properties file is not loaded try to use FileInputStream to load the properties as follows FileInputStream dbin = new FileInputStream("/properties/database.properties"); 您将收到空指针异常,因为未加载属性文件,请尝试使用FileInputStream加载属性,如下所示:FileInputStream dbin = new FileInputStream(“ / properties / database.properties”); properties.load(dbin); properties.load(dbin);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM