我目前有以下方法,它允许我选择已在 resources/config.properties 文件中定义的属性
private final Properties properties = new Properties();
{
final ClassLoader loader = getClass().getClassLoader();
try(InputStream config = loader.getResourceAsStream("Resources/config.properties")){
properties.load(config);
} catch(IOException e){
throw new IOError(e);
}
}
但我现在想从类路径中选择我的属性,因此我已将 config.properties 从资源中移出并将其直接放在 src 下。但我很难知道现在需要对我的方法进行哪些更改才能从类路径读取。
最佳答案
Check example here
import java.io.IOError;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class ReaderProp {
public final Properties properties = new Properties();
public ReaderProp()
{
final ClassLoader loader = getClass().getClassLoader();
try(InputStream config = loader.getResourceAsStream("error.properties")){
properties.load(config);
} catch(IOException e){
throw new IOError(e);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ReaderProp readerProp = new ReaderProp();
System.out.println(readerProp.properties.get("E1000_SE_ERROR-CODE"));// output E1000
}
}
Check error.properties
======================
E1000_SE_ERROR-CODE = E1000
关于java - 从类路径而不是从 resources/config.properties 检索属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51645892/