Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/384.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从Java中的类路径加载.properties文件_Java - Fatal编程技术网

从Java中的类路径加载.properties文件

从Java中的类路径加载.properties文件,java,Java,我必须从类路径访问.properties文件。目前我正在直接从resources文件夹访问它。但是现在我想从类路径访问它 当前代码: public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException try { properties.load(new FileInputStream( "src

我必须从类路径访问.properties文件。目前我正在直接从resources文件夹访问它。但是现在我想从类路径访问它

当前代码:

   public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
try {
    properties.load(new FileInputStream(
            "src/resources/config.properties"));
    for (String key : properties.stringPropertyNames()) {
        String value = properties.getProperty(key);
        rate.add(value);
    }
}
}
文件路径为:
src/resources/config.properties

为了部署代码,我们正在创建完整项目的war文件


请建议如何从类路径获取此文件。

您可以使用此命令从类路径加载文件

this.getClass().getClassLoader().getResourceAsStream("config.properties");

如果您处理的是Falth文件,您应该考虑使用<代码> RealStudio

> P>如果您的代码> CONFIG.Frase文件驻留在java类的同一个包上,那么使用“< /P>”
final Properties properties = new Properties();
try (final InputStream stream =
           this.getClass().getResourceAsStream("somefile.properties")) {
    properties.load(stream);
}
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("config.properties");
如果将属性文件放在任何包中,则还应使用包名

InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("com/your_package_name/config.properties");
所以竞争规则应该是这样的

try {
    Properties configProperties = new Properties();
    InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("resources/config.properties");
    configProperties.load(inputStream);
}
catch(Exception e){
    System.out.println("Could not load the file");
    e.printStackTrace();
}
更新: 为了更好地理解,请参见图片


在加载过程中,我必须进行更改??您可以通过以下方式执行
properties.load(this.getClass().getClassLoader().getResourceAsStream(“config.properties”)我正在获取null指针异常属性.load(this.getClass().getClassLoader().getResourceAsStream(“config.pr‌​不动产);;你能帮我看看getClass().getClassLoader().getResourceAsStream()关于这一行吗?getClass().getClassLoader().getResourceAsStream()正在从资源文件夹中的文件创建InputStream。如果出现空指针异常,则表示在
resources
文件夹中找不到该文件。调用类与config.properties在同一类路径中吗?我得到了空指针异常configProperties.load(inputStream);这意味着
inputStream
null
。无法加载。你能在属性文件的位置显示一个快照吗?我有一个war文件,我想从那里访问.prop文件。你能用一个屏幕截图更新你的问题吗?显示你的立场和你想加载哪个属性文件?我已经更新了问题。虽然这段代码可能会回答这个问题,但最好包含一些上下文,解释它如何工作以及何时使用。从长远来看,只使用代码的答案是没有用的。