简体   繁体   English

从不同的文件夹java中读取配置文件

[英]reading config file from different folder java

I am trying to read a config file based on the code here: 我正在尝试根据此处的代码读取配置文件:

http://www.opencodez.com/java/read-config-file-in-java.htm http://www.opencodez.com/java/read-config-file-in-java.htm

So I found that if the config.cfg is in same directory as of where I am running the code, then everything is fine but if the config is at different directory 所以我发现,如果config.cfg与运行代码的目录位于同一目录中,那么一切都很好,但是如果config位于其他目录中

example: /path/to/config.cfg

I get this error: 我收到此错误:

java.lang.NullPointerException
at java.util.Properties$LineReader.readLine(Properties.java:418)
at java.util.Properties.load0(Properties.java:337)
at java.util.Properties.load(Properties.java:325)
at packagename.conf.Config.<init>(Config.java:14)
at packagename.conf.Config.main(Config.java:30)

My guess is it is not able to find the file. 我的猜测是找不到文件。 But how do I modify the above code to read config file from a different folder? 但是,如何修改上面的代码以从其他文件夹读取配置文件? Thanks 谢谢

Edit: Code from the link: 编辑:链接中的代码:

import java.util.*;
import java.util.Properties;

public class Config 
{
   Properties configFile;
   public Config()
   {
    configFile = new java.util.Properties();
    try {           
      configFile.load(this.getClass().getClassLoader().
      getResourceAsStream("myapp/config.cfg"));         
    }catch(Exception eta){
        eta.printStackTrace();
    }
   }

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

The code that you posted expects the configuration-file to be on the classpath (that is, in the same sorts of places that Java looks for your .class files). 您发布的代码期望配置文件位于类路径上(即Java查找.class文件的位置相同)。 So, you can either include the directory containing the configuration-file in the classpath: 因此,您可以在类路径中包含包含配置文件的目录:

java   -classpath .:/path/to   packagename.conf.Config

Or else you can modify the code to expect the configuration-file to be a regular filesystem file: 否则,您可以修改代码以使配置文件成为常规文件系统文件:

final InputStream cfg = new FileInputStream("/path/to/config.cfg");
try
    { configFile.load(cfg); }
finally
    { cfg.close(); }

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

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