如何在java中加载属性文件而不单独调用laod方法

sar*_*man 1 java

如何在java中加载属性文件而不单独调用laod方法我想在实例化属性对象本身时加载文件.就像我粘贴在下面,但我无法成功.

class test{
Properties configFile = new Properties(load(new FileInputStream("config.properties"));
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 5

只需创建一个单独的方法来执行此操作 - 可能在您可以在其他地方使用的帮助程序类中:

public class PropertiesHelper {
    public static Properties loadFromFile(String file) throws IOException {
        Properties properties = new Properties();
        FileInputStream stream = new FileInputStream(file);
        try {
            properties.load(stream);
        } finally {
            stream.close();
        }
        return properties;
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,由于a的可能性IOException,你仍然需要小心你从哪里调用它.如果要在实例初始化程序中使用它,则需要声明所有构造函数都可以抛出IOException.