我有一个 Maven 项目,我使用 Windows 提示符(控制台)安装并运行该项目。每次运行它时,我都会收到 FileNotFoundException
:
public Properties getConfigProperties() throws Exception {
ClassLoader loader = getClass().getClassLoader();
File file = new File(loader.getResource("config.properties").getFile());
config.load(new FileReader(file));
return config;
}
或者NullPointerException
(如果我使用classpath:config.properties
)。
config.properties
文件位于 /src/main/resources/
文件夹内。
此外,如果我在 IDE 中运行该项目,它会成功完成,不会发生任何异常。
那么我使用控制台命令时出现什么问题呢?
最佳答案
相反
File file = new File(loader.getResource("config.properties").getFile());
使用
File file = new File(loader.getResourceAsStream("config.properties"));
将 xml 文件加载到类路径中的另一种方法是使用 Spring 框架,如下所示:
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
resolver.getResources("classpath*:your/package/**/config.properties");
关于java - 使用记事本出现 FileNotFoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38325430/