我们在一个驱动器上有一个文件 (C:\megzs\realm.properties)。我们想加载这个文件并使用 Spring 中可用的 ClassPathResource 读取内容。但是我们看到文件没有找到异常。我们正在尝试的代码是
Resource resource = new ClassPathResource("file:c:/megzs/realm.properties");
Properties prop = PropertiesLoaderUtils.loadProperties(resource);
Run Code Online (Sandbox Code Playgroud)
这里我们使用 ClassPathResource 来加载外部文件。ClassPathResource 可以加载外部文件吗?
我们如何加载多个属性文件(一个来自类路径,另一个来自绝对路径)??
小智 7
如果您想访问基于文件的资源,请使用 FileSystemResource 并将其提供给 PropertiesLoaderUtils.loadProperties() 方法。下面的代码从文件系统读取属性文件,如果不存在,它将从类路径加载它。希望能帮助到你。
public static Properties getProperties(String propertyFile) {
try {
Resource resource = new FileSystemResource(propertyFile);
if (!resource.exists()) {
resource = new ClassPathResource(propertyFile);
}
return PropertiesLoaderUtils.loadProperties(resource);
} catch (Exception ignored) {
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7749 次 |
| 最近记录: |