Java Check Locale is available using Apache Commons Lang
Tags: LocaleUtils Apache Commons Apache Commons Lang Locale
In this Java tutorial we learn how to use the LocaleUtils class of Apache Commons Lang library to check if a given Locale object is existing on available installed locales.
How to add Apache Commons Lang 3 library to your Java project
To use the Apache Commons Lang 3 library in the Gradle build project, add the following dependency into the build.gradle file.
implementation 'org.apache.commons:commons-lang3:3.12.0'
To use the Apache Commons Lang 3 library in the Maven build project, add the following dependency into the pom.xml file.
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
To have more information about the Apache Commons Lang 3 library you can visit the library home page at commons.apache.org/proper/commons-lang/
How to check a Locale is available in Java
The Apache Commons Lang library provides the method LocaleUtils.isAvailableLocale() to check if a Locale object is existing in the list of available locales. You can learn how to use this method in the below example code.
CheckAvailableLocale.java
import org.apache.commons.lang3.LocaleUtils;
import java.util.Locale;
public class CheckAvailableLocale {
public static void main(String... args) {
Locale locale1 = new Locale("en");
Locale locale2 = new Locale("abc");
boolean result1 = LocaleUtils.isAvailableLocale(locale1);
boolean result2 = LocaleUtils.isAvailableLocale(locale2);
System.out.println("Locale " + locale1 + " available: " + result1);
System.out.println("Locale " + locale2 + " available: " + result2);
}
}
Locale en available: true
Locale abc available: false
Happy Coding 😊