【问题标题】:How to access java properties file如何访问java属性文件
【发布时间】:2016-09-09 19:57:28
【问题描述】:

我有一个属性文件。

#My properties file
config1=first_config
config2=second_config
config3=third_config
config4=fourth_config

我有一个在小型 Java 应用程序中加载属性文件的类。它工作正常,特别是当我尝试访问此类方法中的每个属性时。

public class LoadProperties {
  public void loadProperties() {
    Properties prop = new Properties();
    InputStream input = null;
    try {
        input = new FileInputStream("resources/config.properties");
        prop.load(input);

    } catch (Exception e) {
        System.out.println(e);
    }
  }
}

我正在另一个类中,在一个方法中调用该类的方法。

public class MyClass {
  public void myMethod() {
    LoadProperties lp = new LoadProperties();
    lp.loadProperties();
    /*..More code...*/
  }
}

如何访问MyClass 类中myMethod 方法中的属性? 我尝试输入prop.getProperty("[property_name]"),但不起作用。

有什么想法吗?我假设这将是我访问属性的方式。我可以将它们存储在 loadProperties 类中的变量中并返回变量,但我认为我可以按照上面所说的方式访问它们。

【问题讨论】:

    标签: java class properties getproperties


    【解决方案1】:

    您可以更改 LoadProperties 类以加载属性并添加一个方法来返回加载的属性。

    public class LoadProperties {
        Properties prop = new Properties();
        public LoadProperties() {
            try (FileInputStream fileInputStream = new FileInputStream("config.properties")){
                prop.load(fileInputStream);
            } catch (Exception e) {
                System.out.println(e);
            }
        }
    
        public Properties getProperties() {
            return prop;
        }
    }
    

    那就这样用吧

    public class MyClass {
        public void myMethod() {
            LoadProperties loadProperties = new LoadProperties();
            System.out.println(loadProperties.getProperties().getProperty("config1"));
        }
    }
    

    【讨论】:

    • 同问题代码,不要关闭FileInputStream。完成后必须关闭流,最好使用try-with-resources
    • 我知道,我很懒,只回答原始问题。还应该实现适当的异常处理,而不是使用 System.out.println
    猜你喜欢
    • 1970-01-01
    • 2011-03-18
    • 1970-01-01
    • 2020-11-18
    • 1970-01-01
    • 2014-06-15
    • 1970-01-01
    • 2012-09-29
    • 1970-01-01
    相关资源
    最近更新 更多