在 Java 中加载属性文件 [英] Load a property file in Java

查看:50
本文介绍了在 Java 中加载属性文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当我尝试通过以下方法加载属性文件时.我在 getClass() as-

Whenever I try to load a properties file by below method. I get an error on getClass() as-

无法从 Object 类型对非静态方法 getClass() 进行静态引用

Cannot make a static reference to the non-static method getClass() from the type Object

public static void main(String[] args) {

        ---
        ---

    loadProperties(line);

}

private static void loadProperties(String line) {
        Properties prop = new Properties();
        InputStream in = getClass().getResourceAsStream("foo.properties");
        try {
            prop.load(in);
            for(Object str: prop.keySet()) {
                Object value = prop.getProperty((String) str);
                System.out.println(str+" - "+value);
            }
            in.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    }

关于如何克服这个问题的任何建议.

Any suggestions how can I overcome this.

推荐答案

您不能从静态方法调用 getClass.您要么需要在非静态方法中执行此操作:

You can't call getClass from a static method. You either need to do this in a non-static method:

class MyClass {
   public static void main(String[] args) {
      MyClass obj = new MyClass();
      obj.loadProperties(line);    
   }

   private void loadProperties(String line) {
        Properties prop = new Properties();
        InputStream in = getClass().getResourceAsStream("foo.properties");
        ...  
   }
}

或使用类文字,它在静态上下文中工作,例如

or use a class literal, which does work in a static context, e.g.

InputStream in = MyClass.class.getResourceAsStream("foo.properties");

这篇关于在 Java 中加载属性文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆