gpt4 book ai didi

java - 如何在不单独调用laod方法的情况下在java中加载属性文件

转载 作者:行者123 更新时间:2023-11-29 06:42:10 25 4
gpt4 key购买 nike

如何在不单独调用 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 的可能性,您仍然需要小心调用它的位置。如果您想在实例初始化程序中使用它,您需要声明所有构造函数都可以抛出 IOException

关于java - 如何在不单独调用laod方法的情况下在java中加载属性文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10269112/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com