【问题标题】:properties.getProperty(key) method returns null valueproperties.getProperty(key) 方法返回空值
【发布时间】:2014-09-24 15:26:58
【问题描述】:

我正在加载属性文件并从该文件中获取值,但是当我使用 "Properties" 类和 getProperty(key) 方法时,它返回 null 值。

代码:

public class LoadPropertiesFile {

public static String getProperty (String key, String filePath) {
    Properties properties = new Properties();
    InputStream inputStream = null;
    String value = null;
    try {
        String appHome = ConfigUtil.getApplicationHome() + filePath; 
        inputStream = new FileInputStream(appHome);

        //load a properties file
        properties.load(inputStream);

        //get the property value 
        System.out.println(properties.getProperty("7"));   //print **Unlock**
        System.err.println(key);   //print **7**
        System.out.println(value);   //print **null**
        value = properties.getProperty(key);

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch(IOException e) {
                e.printStackTrace();
            }
        }
    }
    return value;
}
}

输出:

Unlock
7 
null

属性文件:

2=Interactive
3=Network
4=Batch
5=Service
7=Unlock
8=Network Cleartext
10=Remote Desktop
11=Logon with cached credentials

调用方法:

logonType = new LoadPropertiesFile().getProperty("7", "path");

当我调用该方法时,它只会返回 null 值。请帮帮我。

【问题讨论】:

  • 您希望int i; System.out.println(i); i = 5; 打印什么? (不要尝试;猜测)
  • @immibis 我想你想说*打印 5,而不仅仅是打印 ;)
  • @1337 这是一个问题。 “你希望 做什么?”
  • @immibis 你编辑了吗? O_o 我发誓之前没有“什么”……;)

标签: java swing jakarta-ee properties-file


【解决方案1】:

您正在使用 null 初始化值。

String value = null;

然后您打印后分配它:

System.out.println(value);
value = properties.getProperty(key);

输出: null

所以 value 只能在打印时为 null,因为在 System.out.println(value); 之前你永远不会更改它的值。 只需切换这两个语句:

value = properties.getProperty(key);
System.out.println(value);

输出: unlock

编辑

properties.getProperty(key) 也可能返回 null,但前提是其表中没有这样的键,否则它将返回分配的值,在您的示例中为 unlock

有关详细信息,请参阅 API 文档:

public String getProperty(String key)

在此属性列表中搜索具有指定键的属性。如果没有找到密钥 此属性列表、默认属性列表及其默认值, 递归地,然后检查。该方法返回 null 如果属性 没有找到。

http://docs.oracle.com/javase/7/docs/api/java/util/Properties.html#getProperty(java.lang.String)

【讨论】:

    【解决方案2】:
    System.out.println(value);   //print **null**
    value = properties.getProperty(key);
    

    切换这两行并初始化value打印之前:

    value = properties.getProperty(key);
    System.out.println(value);   //print Unlock
    

    【讨论】:

    • 这个方法会返回null吗?
    • @user32118114 properties.getProperty(key) 如果没有这样的密钥,将返回 null,但在这种情况下,它将返回“解锁”。
    • @user3218114 如果(且仅当)密钥不存在时,它将返回 null。
    • @BackSlash 你的回答说了什么。
    • 按照输出方法不应该返回空值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-26
    • 1970-01-01
    • 2017-01-14
    • 1970-01-01
    • 2018-06-01
    相关资源
    最近更新 更多