简体   繁体   English

从Jar Java外的配置文件中读取

[英]Reading From Config File Outside Jar Java

Currently I am trying to read my config file from root of project directory, in order to make this actual configuration I want to move this to external location and then read from there. 目前我正在尝试从项目目录的根目录中读取我的配置文件,为了使这个实际配置我想将其移动到外部位置然后从那里读取。

Adding a complete path in following code throws out error : 在以下代码中添加完整路径会引发错误:

package CopyEJ;

import java.util.Properties;

public class Config
{
   Properties configFile;
   public Config()
   {
    configFile = new java.util.Properties();
    try {
     // configFile.load(this.getClass().getClassLoader().getResourceAsStream("CopyEJ/config.properties"));
      Error Statement ** configFile.load(this.getClass().getClassLoader().getResourceAsStream("C://EJ_Service//config.properties"));
    }catch(Exception eta){
        eta.printStackTrace();
    }
   }

   public String getProperty(String key)
   {
    String value = this.configFile.getProperty(key);
    return value;
   }
}

Here's the error: 这是错误:

java.lang.NullPointerException
    at java.util.Properties$LineReader.readLine(Properties.java:365)
    at java.util.Properties.load(Properties.java:293)
    at CopyEJ.Config.<init>(Config.java:13)
    at CopyEJ.CopyEJ.main(CopyEJ.java:22)
Exception in thread "main" java.lang.NullPointerException
    at java.io.File.<init>(File.java:194)
    at CopyEJ.CopyEJ.main(CopyEJ.java:48)

How can I fix this ? 我怎样才能解决这个问题 ?

The purpose of method getResourceAsStream is to open stream on some file, which exists inside your jar. 方法getResourceAsStream的目的是打开一些文件中的流,该文件存在 jar中。 If you know exact location of particular file, just open new FileInputStream . 如果您知道特定文件的确切位置,只需打开新的FileInputStream

Ie your code should look like: 即您的代码应如下所示:

try (FileInputStream fis = new FileInputStream("C://EJ_Service//config.properties")) {
     configFile.load(fis);
} catch(Exception eta){
     eta.printStackTrace();
}

This line requires your config.properties to be in the java CLASSPATH 这一行要求config.properties位于java CLASSPATH中

this.getClass().getClassLoader().getResourceAsStream("C://EJ_Service//config.properties")

When it is not, config.properties won't be accessible. 如果不是,则无法访问config.properties。

You can try some other alternative and use the configFile.load() function to read from. 您可以尝试其他替代方法并使用configFile.load()函数进行读取。

One example would be: 一个例子是:

InputStream inputStream = new FileInputStream(new File("C:/EJ_Service/config.properties"));

configFile.load(inputStream);

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

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