Skip to content

Instantly share code, notes, and snippets.

@qtopie
Last active May 17, 2018 14:55
Show Gist options
  • Save qtopie/813e0755a8d0ed224440b3650182b1cd to your computer and use it in GitHub Desktop.
Save qtopie/813e0755a8d0ed224440b3650182b1cd to your computer and use it in GitHub Desktop.
Handling Plurals in java (i18n) sample code. Reference: https://docs.oracle.com/javase/tutorial/i18n/format/choiceFormat.html
import java.io.IOException;
import java.text.ChoiceFormat;
import java.text.Format;
import java.text.MessageFormat;
import java.text.NumberFormat;
import java.util.Locale;
import java.util.ResourceBundle;
public class App {
public static void main(String[] args) throws IOException {
String baseName = "messages";
Locale locale = Locale.US;
ResourceBundle bundle = ResourceBundle.getBundle(baseName);
// params
double[] fileLimits = { 0, 1, 2 };
String[] fileStrings = { bundle.getString("abc.xyz.noFiles"), bundle.getString("abc.xyz.oneFile"),
bundle.getString("abc.xyz.multipleFiles") };
String pattern = bundle.getString("abc.xyz.pattern");
for (int i = 0; i < 5; i++) {
Object[] messageArguments = { i, "XDisk" };
System.out.println(doSomething(pattern, fileLimits, fileStrings, messageArguments, locale));
}
}
public static String doSomething(String pattern, double[] fileLimits, String[] fileStrings,
Object[] messageArguments, Locale locale) {
MessageFormat messageFormat = new MessageFormat("", locale);
ChoiceFormat choiceFormat = new ChoiceFormat(fileLimits, fileStrings);
messageFormat.applyPattern(pattern);
Format[] formats = { choiceFormat, null, NumberFormat.getInstance() };
messageFormat.setFormats(formats);
return messageFormat.format(messageArguments);
}
}
Hello=Nice to meet you!
abc.xyz.pattern=There {0} on {1}.
abc.xyz.noFiles=are no files
abc.xyz.oneFile=is one file
abc.xyz.multipleFiles=are {0} files
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment