java配置文件

Att*_*lah 0 java java-ee

我有一个方法:

private String getProperty(String property) throws IOException,ConfigException {

    // first test if the config file exists.
    String propertyFile = "DataTransfer/Config/DataTransfer.properties";

    if(!new File(propertyFile).exists()) {
        throw new ConfigException("the config file doesn't exist." +
            " Make sure the file : \""+propertyFile+"\" exists.");
    }   

    // retrieve the property
    Properties configFile = new Properties();

    configFile.load(this.getClass().getClassLoader()
        .getResourceAsStream(propertyFile));

    String prop = configFile.getProperty(property);
    return prop;
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,我一直在java.lang.NullPointerException达到这个ConfigFile.load()水平.

我在调试模式下检查了我的变量,它们都不是null.

我不知道这个例外的原因是什么.

Jon*_*eet 5

您已检查它是否作为当前工作目录中的文件存在.您尚未检查它是否存在于类路径中.

如果您知道它作为文件存在,为什么不将其作为文件加载?

如果要从类路径加载它,为什么不更改检查以确保它存在于类路径中?

基本上,您需要在检查和装载之间保持一致.

  • @Attilah:最尊重的是,如果你不知道如何使用`InputStream`,你就不应该尝试编写J2EE应用程序.首先学习Java的核心部分,然后*继续学习更复杂的主题,比如J2EE. (2认同)