![]() |
|
Tutorial: Using gettext in Java 5 (or later)Since I'm a very big fan of gettext I also use gettext to create the
resource bundles of my Java programs. Here is a short tutorial. Important notice: This tutorial doesn't make use of gted! It demostrates simply the functionality of GNU gettext with Java. 1. Create a class called Utilpublic class Util {
private static ResourceBundle catalog =
ResourceBundle.getBundle("Messages");
public static String _(String s) {
return catalog.getString(s);
}
}
2. Use Util as static import in your classes to mark the strings Translatableimport static Util._; public class Translatable {
public static void main(String[] args) {
System.out.println(_("Text one"));
System.out.println(_("Text two"));
}
}
3. Generate .pot file from your Java sources> xgettext -k_ -o po/messages.pot src/Translatable.java -k_ indicates that the it must scan for calls to _() 4. Copy the .pot file to a .po file for the desired languagesPlace the file under po/<languagecode>/messages.po 5. Generate ResourceBundles> msgfmt --java2 -d resources -r Messages -l de po/de/messages.po Hint: under Windows you have to set the TMPDIR: i.e. set TMPDIR=c:\temp 6. Run the programMake sure that the folder resources is in the classpath! The programs output should now be translated. Appendix. Update .po filesTo update your .po files run again: > xgettext -k_ -o po/messages.pot src/Translatable.java Then merge the new .pot file to the existing .po files > msgmerge -U po/de/messages.po po/messages.pot |