如何在不单独调用 laod 方法的情况下在 java 中加载属性文件我想在属性对象本身的实例化时加载文件。就像我在下面粘贴的一样,但我无法成功。
class test{
Properties configFile = new Properties(load(new FileInputStream("config.properties"));
}
如何在不单独调用 laod 方法的情况下在 java 中加载属性文件我想在属性对象本身的实例化时加载文件。就像我在下面粘贴的一样,但我无法成功。
class test{
Properties configFile = new Properties(load(new FileInputStream("config.properties"));
}
只需创建一个单独的方法来执行此操作 - 可能在您可以在其他地方使用的辅助类中:
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;
}
}
请注意,由于 的可能性IOException
,您仍然需要小心从哪里调用它。如果要在实例初始化程序中使用它,则需要声明所有构造函数都可以 throw IOException
。
类似这样的东西:
class Test {
Properties configFile = new Properties() {{ load(new FileInputStream("config.properties")); }};
}
您实际上是在此处对 Properties 进行子类化并使用其初始化部分。load(..) 可能会抛出一个异常,如果你需要添加一个try { ... } catch () {}