config.properties 文件未在 java 中读取

The config.properties file is not read in java

我的文件夹结构如下:

>test
    >src
         >org.mypackage
                >myclass
    >resources
         >config.properties

javaclass如下:

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;    

public myclass {

     private String path = "config.properties";

     public myclass() {
         Properties prop = new Properties();
         InputStream input = null;
         try {
             input = getClass().getClassLoader().getResourceAsStream(path);
             prop.load(input)
         }
         catch(Exception ex) {
             ex.printStackTrace();
         }
    }
}

但我在调试期间得到 null 作为 input 的值。

在调试模式下我检查了 getClass() 的值,我得到了 class 值,该值也可用于 getClass().getClassLoader() 但对于 getClass().getClassLoader().getResourceAsStream(path) 它是null

我不确定是什么问题。

感谢您的帮助!

你应该在这里检查这个问题,这应该有助于你回答你的问题:How to add a Java Properties file to my Java Project in Eclipse

此外,在我看来,您的项目并不是 100% Maven 兼容的。你应该有更多类似的东西:

>src
    >main
        >java
        >resources
    >test
        >java
        >resources

那么 Eclipse 在处理和加载您的属性时应该不会丢失。

如果您有任何问题,请随时给我留言

resources 似乎不是您的 Eclipse 项目中的源文件夹。尝试将 resources 设置为源文件夹:

Right click > Build Path > Use as Source Folder