Locale Language Tag Roundtrip
Parse BCP 47 tags into Locale objects with forLanguageTag, build canonical tags back with Locale.Builder, and watch ill-formed tags resolve to und.
Code
import java.util.Locale;
public class AcceptLanguageRouter {
public static void main(String[] args) {
// BCP 47 标签 -> Locale 对象
for (String tag : new String[] {"en-US", "zh-CN", "pt-BR", "zh-Hant-TW"}) {
Locale parsed = Locale.forLanguageTag(tag);
System.out.println(tag + " -> " + parsed.getLanguage()
+ "/" + parsed.getCountry()
+ " (" + parsed.getDisplayLanguage(Locale.ENGLISH) + ")");
}
// Locale.Builder 按 language-script-region 规范顺序重组标签
Locale rebuilt = new Locale.Builder()
.setLanguage("zh")
.setScript("Hant")
.setRegion("TW")
.build();
System.out.println("rebuilt tag: " + rebuilt.toLanguageTag());
// 语法非法的标签:解析失败得到 und(未确定),而不是抛异常
Locale illFormed = Locale.forLanguageTag("en_**");
System.out.println("invalid tag language: " + illFormed.getLanguage());
}
}How it works
Under the hood: the class AcceptLanguageRouter and the function main.
for (String tag : new String[] {"en-US", "zh-CN", "pt-BR", "zh-Hant-TW"}) is the loop that carries the per-item work. Resources are declared in a try-with-resources header, so they close on every exit path without a finally block.
Applying it
Running the file prints labeled results such as rebuilt tag:, invalid tag language: — each operation’s effect is visible in the output.
Statements that matter
Locale illFormed = Locale.forLanguageTag("en_**");
Locale parsed = Locale.forLanguageTag(tag);
Locale rebuilt = new Locale.Builder()
.setLanguage("zh")
.setScript("Hant")
.setRegion("TW")
.build();
Interactive Tools for This Topic
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
FAQ
- What does Locale Language Tag Roundtrip print when run?
- No setup needed: run the file and look for labeled lines like `rebuilt tag:`, `invalid tag language:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.