java - 在java程序中加载属性

标签 java properties

我是一名初级java程序员;现在我正在使用 J2SE 和 NetBeans 6.9.1 来编写应用程序代码。

我现在面临的问题是使用单例类从本地文件系统中的众所周知的位置加载属性。令我恼火的是,我收到一个错误,该错误声称存在 throws 子句或捕获正在初始化 INSTANCE 变量的异常。希望有人能帮助我理解这一点。

提前致谢。

代码如下:

package cat.oai.atapplications.phot;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

/**
 *
 * @author fdalmau
 */
public class PhotPropertiesManager {

    private static Properties photProperties;

    private PhotPropertiesManager() throws FileNotFoundException, IOException {
        photProperties = LoadProperties();
    }

    public static PhotPropertiesManager getInstance() {
        return PhotPropertiesManagerHolder.INSTANCE;
    }

    public static Properties getPhotProperties() {
        return PhotPropertiesManager.photProperties;
    }

    private static Properties LoadProperties() throws FileNotFoundException,
                                                      IOException {

        Properties defaultPhotProperties = new Properties();

        FileInputStream in = new FileInputStream("defaultphot");
        defaultPhotProperties.load(in);
        in.close();

        Properties applicationPhotProperties = 
                                     new Properties(defaultPhotProperties);

        in = new FileInputStream("lastexecutionphot");
        applicationPhotProperties.load(in);
        in.close();

        return applicationPhotProperties;
    }

    private static class PhotPropertiesManagerHolder {

        /******
          The problem is is this line of code:
         ******/
        static final PhotPropertiesManager INSTANCE = new PhotPropertiesManager();

    }
}

最佳答案

问题是静态字段不能抛出检查异常。我会像这样简化代码。

public enum PhotPropertiesManager {;
    private static final Properties PHOT_PROPERTIES = new Properties();

    static {
        try {
            load("defaultphot");
            load("lastexecutionphot");
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }
    }

    private static void load(String filename) throws IOException {
        FileInputStream in = new FileInputStream(filename);
        PHOT_PROPERTIES.load(in);
        in.close();
    }

    public static Properties getPhotProperties() {
        return PHOT_PROPERTIES;
    }
}

关于java - 在java程序中加载属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8417667/

相关文章:

java - java写入随机位置的txt文件

java - 如何将按钮背景更改为图像,然后在按下时返回默认按钮

java - Maven:每个标签上都出现不可解析的 POM 无法识别的标签错误

java - 为什么不使用 java web start 而不是其他 RIA 框架?

c# - 如何在 ISO C++ 中定义或实现 C# 属性?

swift - 使用变量值进行属性查找

iphone - 为什么自动生成的 IBOutlet @properties 不使用 @synthesize button = _button 约定?

java - 无法显示代号为 1 的 Web 服务调用的响应

c# - 有没有办法将属性的 setter 传递给委托(delegate)?

c# - 在 C# 中公开数组元素的属性