2010-06-01 23 views

回答

9

你有兩個選擇:

  • java.util.Formatter
    • printf風格的格式字符串的解釋。此類提供對佈局對齊和對齊的支持,數字,字符串和日期/時間數據的常用格式以及特定於語言環境的輸出。
  • java.text.MessageFormat
    • MessageFormat提供了一種以與語言無關的方式產生級聯消息的方法。使用它來構造顯示給最終用戶的消息。

在這兩個,MessageFormat是迄今爲止功能更強大。下面是使用ChoiceFormat處理01的一個例子,>1情況不同,:

import java.text.MessageFormat; 
import java.util.Date; 
//... 

String p = "You have {0,choice,0#none|1#one ticket|1<{0,number,integer} tickets} for {1,date,full}."; 
for (int i = 0; i < 4; i++) { 
    System.out.println(MessageFormat.format(p, i, new Date())); 
} 

此打印:

You have none for Tuesday, June 1, 2010. 
You have one ticket for Tuesday, June 1, 2010. 
You have 2 tickets for Tuesday, June 1, 2010. 
You have 3 tickets for Tuesday, June 1, 2010. 

的文檔有更多的例子。

4

String.format是最簡單的:

String s = String.format("%s %s", "Hello", "World!"); 

可以用的參數的可變數量調用它,我等上面顯示,或通過它的Object陣列,它會使用它。

4

下面應該工作:

import java.util.*; 


class Brr { 
    String template; 
    Object[] args; 
    public Brr(String template, Object... args) { 
     this.template = template; 
     this.args = args; 
    } 
    public void print() { 
     System.out.println(String.format(template, args)); 
    } 
} 

public class Test { 
    public static void main(String... args) { 
     String template = "You have %d tickets for %tF"; 
     Brr object = new Brr(template, new Integer(1), new Date()); 
     object.print(); 
    } 
} 

輸出:如果你想轉換的完整參考

You have 1 tickets for 2010-06-01 

看一看http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html

1

MessageFormat.format()允許我使用序參數,因此很容易實現國際化

private final Map<String, String> localizedMessages = new HashMap<String, String>(); 

private void init() { 
    this.localizedMessages.put("de_DE", "{2} Suchtreffer, zeige Ergebnisse ${0} bis ${1}"); 
    this.localizedMessages.put("en_US", "Showing results {0} through {1} of a total {2"); 
} 

public String getLocalizedMessage(final String locale, 
     final Integer startOffset, final Integer endOffset, 
     final Integer totalResults) { 
    return MessageFormat.format(this.localizedMessages.get(locale), 
      startOffset, endOffset, totalResults); 

} 
0

節奏java的模板現在有新的功能發佈引擎調用String interpolation mode,它允許你做這樣的事情:

String result = Rythm.render("You have @num tickets for @date", 1, new Date()); 

上述情況顯示您可以按位置將參數傳遞給模板。節奏還允許您通過名字來傳遞參數:

Map<String, Object> args = new HashMap<String, Object>(); 
args.put("num", 1); 
args.put("date", new Date()); 
String result = Rythm.render("You have @num tickets for @date", args); 

鏈接:

相關問題