Java 如何知道属性文件中是否存在属性?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2920013/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 14:29:24  来源:igfitidea点击:

How to know whether a property exists or not in a property file?

java

提问by user351809

How to know whether a property exists or not in a property file in java?

如何知道属性是否存在于java中的属性文件中?

回答by crazyscot

According to http://java.sun.com/javase/6/docs/api/java/util/Properties.html, getProperty()returns nullif the property was not found. You could also call propertyNames()or stringPropertyNames()and look to see whether the property name of interest is in the returned set.

根据http://java.sun.com/javase/6/docs/api/java/util/Properties.html,如果未找到该属性,则getProperty()返回null。您还可以调用propertyNames()stringPropertyNames()查看感兴趣的属性名称是否在返回的集合中。

回答by miku

Just load the properties file and then try to get the desired property.

只需加载属性文件,然后尝试获取所需的属性。

public String getProperty(String key)

Searches for the property with the specified key in this property list. If the key is not found in this property list, the default property list, and its defaults, recursively, are then checked. The method returns null if the property is not found.

在此属性列表中搜索具有指定键的属性。如果在此属性列表中找不到该键,则递归地检查默认属性列表及其默认值。如果未找到该属性,该方法将返回 null。

回答by David Soroko

You can also call getProperty(String key, String defaultValue)and check if the return value is the defaultValue.

您还可以调用getProperty(String key, String defaultValue)并检查返回值是否为defaultValue.

See https://docs.oracle.com/javase/8/docs/api/java/util/Properties.html#getProperty-java.lang.String-java.lang.String-

请参阅https://docs.oracle.com/javase/8/docs/api/java/util/Properties.html#getProperty-java.lang.String-java.lang.String-

回答by abovesun

Here is some trick how to find out is some file (not mandatory property file) exists in class path

这里有一些技巧如何找出类路径中是否存在某个文件(非强制属性文件)

public class FileUtil {
    public static boolean isFileExists(String fileName){
         return null != FileUtil.class.getResourceAsStream(fileName);
    }
}

Sure it not always works as long it depends on class loading aspects

当然它并不总是有效,只要它取决于类加载方面

回答by Miserable Variable

Yet another alternative is to exploit the fact the Properties extends Hashtable<Object,Object>and use containsKey.

另一种选择是利用事实Properties extends Hashtable<Object,Object>和使用containsKey.

回答by vo0

If you want to check that at the start of program you can do the following:

如果您想在程序开始时检查,您可以执行以下操作:

  1. Create a class VerifiedPropertiesthat extends Properties
  2. Add all properties as fields of this class as public final int/String/boolean/etc...
  3. Add private final String propertyNotValid="Property not valid"String to this class
  4. Add private final String propertyNotFound="Property not found"String to this class
  5. Override getProperty()method from Properties class.
  6. You can add @Deprecatedtag to suggest usage of the fields. It is impossible to hide this method because it is public in Properties class.
  7. Initialize all fields in the constructor using getProperty()method or dedicated for type (look examples below)
  1. 创建一个VerifiedProperties扩展的类Properties
  2. 将所有属性作为此类的字段添加为 public final int/String/boolean/etc...
  3. private final String propertyNotValid="Property not valid"字符串添加到此类
  4. private final String propertyNotFound="Property not found"字符串添加到此类
  5. 重写getProperty()Properties 类中的方法。
  6. 您可以添加@Deprecated标签来建议字段的用法。隐藏此方法是不可能的,因为它在 Properties 类中是公共的。
  7. 使用getProperty()方法或专用于类型初始化构造函数中的所有字段(查看下面的示例)

Example methods that takes care of different property types:

处理不同属性类型的示例方法:

@Override
@Deprecated
/*
 Deprecated annotation added to suggest usage of the fields.
 */
public final String getProperty(String key)
{
    String propertyValue = super.getProperty(key);
    if (propertyValue != null)
    {
        return propertyValue;
    }
    else
    {
        throw new NoSuchFieldError(this.propertyNotFound + " " + key);
    }
}
private int getIntegerProperty(String key)
{
    String propertyValue = this.getProperty(key);
    try
    {
        int propertyIntValue = Integer.parseInt(propertyValue);
        return propertyIntValue;
    }
    catch (NumberFormatException e)
    {
        throw new NumberFormatException(this.propertyNotValid + " " + key);
    }
}
private boolean getBooleanProperty(String key)
{
    String propertyValue = this.getProperty(key);
    try
    {
        boolean propertyBooleanValue = Boolean.parseBoolean(propertyValue);
        return propertyBooleanValue;
    }
    catch (NumberFormatException e)
    {
        throw new NumberFormatException(this.propertyNotValid + " " + key);
    }
}
private long getLongProperty(String key)
{
    String propertyValue = this.getProperty(key);
    try
    {
        long propertyLongValue = Long.parseLong(propertyValue);
        return propertyLongValue;
    }
    catch (NumberFormatException e)
    {
        throw new NumberFormatException(this.propertyNotValid + " " + key);
    }
}
@Override
@Deprecated
/*
 Deprecated annotation added to suggest usage of the fields.
 */
public final String getProperty(String key)
{
    String propertyValue = super.getProperty(key);
    if (propertyValue != null)
    {
        return propertyValue;
    }
    else
    {
        throw new NoSuchFieldError(this.propertyNotFound + " " + key);
    }
}
private int getIntegerProperty(String key)
{
    String propertyValue = this.getProperty(key);
    try
    {
        int propertyIntValue = Integer.parseInt(propertyValue);
        return propertyIntValue;
    }
    catch (NumberFormatException e)
    {
        throw new NumberFormatException(this.propertyNotValid + " " + key);
    }
}
private boolean getBooleanProperty(String key)
{
    String propertyValue = this.getProperty(key);
    try
    {
        boolean propertyBooleanValue = Boolean.parseBoolean(propertyValue);
        return propertyBooleanValue;
    }
    catch (NumberFormatException e)
    {
        throw new NumberFormatException(this.propertyNotValid + " " + key);
    }
}
private long getLongProperty(String key)
{
    String propertyValue = this.getProperty(key);
    try
    {
        long propertyLongValue = Long.parseLong(propertyValue);
        return propertyLongValue;
    }
    catch (NumberFormatException e)
    {
        throw new NumberFormatException(this.propertyNotValid + " " + key);
    }
}

Then you can create somewhere:

然后你可以在某处创建:

public static VerifiedProperties properties;

公共静态 VerifiedProperties 属性;

and use the properties that you need as properties.myProperty

并使用您需要的属性作为 properties.myProperty

Advantages:

好处:

  • you have full control over properties which includes exception handling and null checking
  • If property does not exist or is in incorrect format, you will have the information at the initialization of the program
  • You don't need to worry about parsing properties to different types than String in your code.
  • You can add validators to your Stringproperties
  • You can easily refactor property name
  • If you are using external property file that can be modified by the user outside of your application, if provided change is incorrect or there are fields missing your program will not start.
  • 您可以完全控制属性,包括异常处理和空检查
  • 如果属性不存在或格式不正确,您将在程序初始化时获得信息
  • 您无需担心在代码中将属性解析为与 String 不同的类型。
  • 您可以将验证器添加到您的String属性
  • 您可以轻松重构属性名称
  • 如果您使用的外部属性文件可由用户在您的应用程序之外修改,如果提供的更改不正确或缺少字段,您的程序将无法启动。

Disadvantages:

缺点:

  • For each property besides adding value to *.propertiesfile you need to create field and assign value in the constructor. If you have a lot of properties then this file can look unpleasant.
  • 对于每个属性,除了向*.properties文件添加值之外,您还需要在构造函数中创建字段并赋值。如果你有很多属性,那么这个文件可能看起来很不愉快。

Hints:

提示:

  • it is easier to mantain the file if you keep the same name for the field as in properties file.
  • (Netbeans) you can Toggle Rectangular Selectionto add public final Stringand similar to many lines at once.
  • (Netbeans) to keep *.propertiesfile clean you can use this solution.
  • 如果您为该字段保留与属性文件中相同的名称,则更容易维护该文件。
  • (Netbeans) 你可以一次Toggle Rectangular Selection添加public final String和相似多行。
  • (Netbeans) 要保持*.properties文件干净,您可以使用此解决方案

回答by Samir

The answer by crazyscot is now outdated. According to the new javadoc, the property will just get created if it doesn't exist,

crazyscot 的答案现在已经过时了。根据新的javadoc,如果该属性不存在,它将被创建,

"If there is no current set of system properties, a set of system properties is first created and initialized in the same manner as for the getProperties method".

“如果当前没有一组系统属性,则首先以与 getProperties 方法相同的方式创建和初始化一组系统属性”。

回答by selim.aksoy

You can use hasProperty

您可以使用 hasProperty

AllValues.hasProperty("childList")