【问题标题】:Automatically Trim Trailing White Space for properties in Props file loaded into java.util.Properties为加载到 java.util.Properties 的 Props 文件中的属性自动修剪尾随空格
【发布时间】:2018-01-10 12:17:40
【问题描述】:

我正在使用 java.util.Properties 从属性文件中加载属性。有什么方法可以在加载数据时自动删除值的空格? 目前我正在使用:

Properties properties = new Properties();
FileInputStream file = new FileInputStream(/path/to/file);
properties.load(file);

【问题讨论】:

  • 您的意思是在您检索的任何属性值上使用 trim() 以外的其他值?
  • 我的应用需要一次性解决方案
  • 您可以制作一个独立的程序来读取您存储的属性文件,修剪所有值并存储修改后的属性。但是,除非您修复您的应用程序以使其不存储带有尾随空格的属性值,否则它不会是一次性解决方案...
  • 您也可以编写一个新的java.util.Properties 类,所以相同的包,相同的名称,并尝试让 ClassLoader 用它替换原始类。这很老套,你可能会遇到SecurityManager 问题...

标签: java


【解决方案1】:

您可以扩展 Properties 类并覆盖其 getProperty(String key) 方法以返回修剪后的字符串。

public class MyProperties extends Properties {
    @Override
    public String getProperty(String key) {
         return super.getProperty(key).trim();
    }
}

并使用它:

MyProperties properties = new MyProperties ();
FileInputStream file = new FileInputStream(/path/to/file);
properties.load(file);
//Now any propery you get will be returned trimmed
properties.getProperty("test"); //will be returned trimmed

【讨论】:

  • 无论我在哪里使用 Properties 类,都需要重写我的应用程序
  • 有没有更好的办法?
  • 在这种情况下,创建一个在加载之前修剪实际文件的方法不是更容易吗?
  • 您不必将每次出现的Property 更改为MyProperty,只需将new Property() 更改为new MyProperty()。但是,在加载之后或保存之前主动清理属性也是一个非常好的方法。
  • 这有几个问题:1. NPE 如果属性不存在(可修复) 2. 依赖 getProperty(String key,String default) 调用 getProperty(String key)(可能是真的,但不确定) 3. 不起作用对于values() 和存储值的方法。理想的解决方案是修剪“真实”的潜在价值。
【解决方案2】:

我得到的唯一可能的解决方法是,如果它对某人有帮助,这不会影响已经存在的 Properties 类引用。

Properties properties = new Properties();
FileInputStream file = new FileInputStream(/path/to/file);
properties.load(file);
for (Entry<Object, Object> entry : properties.entrySet()) {
    entry.setValue(entry.getValue().toString().trim());
}

【讨论】:

  • 这对性能不利,想象一下有很多条目。此外,如果您按照我在回答中提到的那样扩展类,它不会影响已经存在的类引用;你只会开始初始化新的属性类。
  • 是的,就像我之前说的,如果你想使用@riadrifai 扩展Property 的想法,除了编写MyProperties 类本身之外,你必须做的唯一改变是将new Property() 更改为new MyProperty()。多态性负责剩下的事情......
  • 因为我有这么多类在为 Properties 类做实例化,所以测试同样是一个耗时的过程
  • 所以现在你要在每次实例化后添加循环..?
  • 不是在实例化之后,而是在加载之后,即在properties.load(file)之后;
【解决方案3】:
    Properties config = new Properties();
    String configFile = "config/apps.properties";
    try (FileReader fr = new FileReader(configFile)) {
        config.load(fr);
        System.out.println(config);
        for (String k : config.stringPropertyNames()) {
            config.setProperty(k, config.getProperty(k).trim());
        }
        System.out.println(config);
    } catch (IOException ex) {
        System.out.printf("Error: Failed to load config file %s due to exception: %s\n", configFile, ex.toString());
        System.exit(1);
    }

【讨论】:

  • 为您的答案添加解释将对用户有所帮助
猜你喜欢
  • 2011-10-25
  • 1970-01-01
  • 2012-02-02
  • 2021-03-17
  • 2010-11-26
  • 1970-01-01
  • 1970-01-01
  • 2014-05-07
  • 1970-01-01
相关资源
最近更新 更多