如何解析包含变量的 Java 属性? [英] How to parse Java properties which contains variables?

查看:36
本文介绍了如何解析包含变量的 Java 属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在加载一个 Java 属性文件,它看起来像:

I'm loading a file of Java properties which looks like:

transfer_detail = Transfer {0} from {1} to {2} on {3}

解析该属性后,我应该有如下所示的字符串:

After parsing that property I should have String that looks like:

Transfer 200.30 from Debit Account to Credit Account on 2011/01/26

我自己实现了一个解析器,它看起来像:

I implemented my self a parser which looks like:

// simplified for brevity
private static String translate(String string, String... replacements){
    String result = string;
    for(int i = 0; i < replacements.length; i++){
        result = result.replace("{"+i+"}", replacements[i]);
    }
    return result;
}
// and I use it this way:
String result = translate("transaction", "200.30", "Debit Account", etc...);

我一直想知道在 J2SE API 中是否有这样做的东西.即使对于这样的简单事情,我也不喜欢重新发明轮子.您知道其他更简单或更简洁的方法来实现这一目标吗?

What I've been wondering is if there's something to do so in the J2SE API. Even for simple things like this I don't like to reinvent the wheel. Do you know any other easier or cleaner way to achieve this?

推荐答案

您想使用 MessageFormat,用于用实际值填充占位符.

You want to use the MessageFormat class for filling in the placeholders with actual values.

这篇关于如何解析包含变量的 Java 属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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