如何使用Java ClassLoader从类路径加载文件?

我想使用ClassLoader加载Properties类的属性文件。 为了本次讨论的目的,我简化了以下代码以删除error handling:

loader = this.getClass().getClassLoader(); in = loader.getResourceAsStream("theta.properties"); result = new Properties(); result.load(in); 

在与此类相同的目录中,我有文件“theta.properties”,但InputStream始终为null。 我把文件放在错误的地方吗? 我正在使用eclipse及其设置将类文件构建到源文件夹 – 所以这应该不是问题。

我在JavaDoc中找不到任何东西让ClassLoader告诉我正在搜索什么类路径。

通过使用getClass().getClassloader()您可以从根路径目录中查找“theta.properties”。 只需使用getClass().getResourceAsStream()来获取相对于该类的资源。

如果文件与类位于同一目录中,则必须将类的包作为目录作为前缀。

所以,如果您的包裹是:

 package com.foo.bar; 

然后你的代码是:

 .getResourceAsStream("com/foo/bar/theta.properties"); 

您可以使用ResourceBundle