home

Internationalization and Localization

Locale

Locales are used to tailor data for a specific region.

Displaying the default Locale

Locale.getDefault(); // en_CA

Displaying Locale Language and Country in different Locales

Locale it = new Locale("it", "IT");
Locale fr = new Locale("fr", "FR");

// What is Italian in French?
it.getDisplayLanguage(fr);
// italien

// What is Italy in French?
it.getDisplayCountry(fr);
// Italie

// What is French in Italian?
fr.getDisplayLanguage(it);
// francese

// What is France in Italian?
fr.getDisplayCountry(it);
// Francia

// If no specific Locale is supplied, default Locale is used in both methods
// For me, it would be: What is Italian in Locale en_CA
// For me, it would be: What is French in Locale en_CA

Properties

System Properties

java.util.Properties p = System.getProperties();
p.list(System.out);

Sample output (truncated)

user.dir=/Users/kt
java.runtime.version=1.8.0_202-b08
user.home=/Users/kt
java.version=1.8.0_202
file.separator=/
file.encoding=UTF-8

Creating Properties Files

Properties properties = new Properties();
properties.setProperty("foo", "bar");
try (FileOutputStream fos = new FileOutputStream("app.properties")) {
    properties.store(fos, null);
} catch (IOException ignored) {}

app.properties is created with the following contents

#Thu Feb 14 21:05:27 EST 2019
foo=bar

Reading Properties Files

Properties properties = new Properties();
try (FileInputStream fis = new FileInputStream("app.properties")) {
    properties.load(fis);
    properties.getProperty("foo");  // bar
} catch (IOException ignored) {}

Methods to Remember Using Properties

void load(InputStream inStream);
void list(PrintStream out);
Object setProperty(String key, String value);
String getProperty(String key);
void store(OutputStream out, String headerComment);

Resource Bundles

app.properties

greeting=Hello World!
ResourceBundle rb = ResourceBundle.getBundle("app");  // filename must end with .properties
rb.getString("greeting");                             // Hello World!

Getting a Resource Bundle with a Specific Locale

app_tr.properties

greeting=Hello World!
ResourceBundle rb = ResourceBundle.getBundle("app", new Locale("tr"));
rb.getString("greeting"); // Merhaba Dunya!