Is there a good alternative to gettext _ () method in Java?

This is the usual way to separate text messages and source code from C / Python / PHP / etc using the gettext utility set. I am trying to do something similar in my Java project according to this instruction . Is this the best way? Or should I try something different and more advanced?

ps. I would like to avoid complicated initialization, and ideally my Java code should look like this:

[...] public String howBigIsTheFile(File f) { String name = f.getAbsolutePath(); long length = f.length(); return _("The file %s is %d bytes long", name, length); } 

Something like gettext-commons maybe?

+4
source share
2 answers

I assume this question relates to a standalone application (command line, SWING, etc.), and not to a server application (with multiple users accessing simultaneously).

In a stand-alone application, it is easiest to create one static accessor class that will be responsible for loading a single resource package , and then searching for strings in that resource package.

Something like that:

 public class ResourceUtil { private static ResourceBundle rb; static { //set the default locale setLocale(Locale.ENGLISH); } public static void setLocale(Locale locale) { rb = ResourceBundle.getBundle("Resources", locale); } public static String tr(String key, Object... args) { return MessageFormat.format(rb.getString(key), args); } } 

You can change the active language using the setLocale(Locale) method and access the translated strings using the tr(String,Object...) method.

Then you can call it from your class as follows:

 import static ResourceUtil.tr; public String howBigIsTheFile(File f) { String name = f.getAbsolutePath(); long length = f.length(); return tr("The file %s is %d bytes long", name, length); } 

Pay attention to static imports.

Disclaimer : All provided code is at the pseudo-code level and cannot be compiled.

Depending on the size of your application, it may be useful to use emergency support for IDE strings (for example, see the Eclipse JDT help chapter, I'm sure other IDEs have some similar features).

You can also use several resource packages and / or several static classes - this depends on the size of your application and your personal preferences. See this question for further discussion of this issue.

In a server environment that uses a static approach, such as the one above, a problem may occur because different users will have different locales. Depending on your webapp platform, you would solve this problem differently (for example, use MessageSource in Spring ).

+3
source

If you are thinking about the I18N / L10N, Java has its own mechanism here: a properties file. You can see an example in internationalization textbooks . This is even simpler than gettext :) stuff.

0
source

All Articles