Last active
May 17, 2018 14:55
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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