此代码段中的示例向您展示了如何获取可用的货币代码。Currency在此示例中,我们将需要区域设置信息并使用该类。
package org.nhooo.example.util;
import java.util.Currency;
import java.util.Locale;
import java.util.Map;
import java.util.TreeMap;
public class CurrencySymbolDemo {
public static void main(String[] args) {
CurrencySymbolDemo cs = new CurrencySymbolDemo();
Map<String, String> currencies = cs.getAvailableCurrencies();
for (String country : currencies.keySet()) {
String currencyCode = currencies.get(country);
System.out.println(country + " => " + currencyCode);
}
}
/**
* Get the currencies code from the available locales information.
*
* @return a map of currencies code.
*/
private Map<String, String> getAvailableCurrencies() {
Locale[] locales = Locale.getAvailableLocales();
// 我们使用TreeMap,以便对映射中的数据顺序进行排序
// 根据国家名称。
Map<String, String> currencies = new TreeMap<>();
for (Locale locale : locales) {
try {
currencies.put(locale.getDisplayCountry(),
Currency.getInstance(locale).getCurrencyCode());
} catch (Exception e) {
// 不支持语言环境时
}
}
return currencies;
}
}屏幕上将显示以下内容:
... Honduras => HNL Hong Kong => HKD Hungary => HUF Iceland => ISK India => INR Indonesia => IDR Iraq => IQD Ireland => EUR Israel => ILS Italy => EUR ...