如何在java中验证语言环境?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3684747/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 03:29:06  来源:igfitidea点击:

How to validate a locale in java?

javalocale

提问by u123

I read a file in an application that specifies a language code:

我在指定语言代码的应用程序中读取了一个文件:

public void setResources(String locale) {

    // validate locale
    // ULocale lo = new ULocale(locale);
    // System.out.println(lo.getDisplayCountry());

}

that must be in the format: <ISO 639 language code>_<ISO 3166 region code>eg. en_UK, en_US etc. Is it possible to validate that the locale string is valid before continuing?

必须采用以下格式:<ISO 639 language code>_<ISO 3166 region code>例如。en_UK、en_US 等。是否可以在继续之前验证语言环境字符串是否有效?

采纳答案by u123

Now I just do:

现在我只做:

ULocale uLocale = new ULocale(locale);
if (uLocale.getCountry() != null && !uLocale.getCountry().isEmpty()) {
  ...
}

which works fine.

这工作正常。

回答by locka

You can get the available locales like so and enumerate them to see if the locale is valid

您可以像这样获取可用的语言环境并枚举它们以查看语言环境是否有效

boolean isValidLocale(String value) {
  Locale[] locales = Locale.getAvailableLocales();
  for (Locale locale : locales) {
    if (value.equals(locale.toString())) {
      return true;
    }
  }
  return false;
}

回答by kostja

You could check if the String is contained in the Arrays returned by the getISOCountries()or getISOLanguages()methods of Locale. Its kinda crude but may actually work. You could also extract all available Localeswith getAvailableLocales()and search them for display names.

您可以检查 String 是否包含在 的getISOCountries()getISOLanguages()方法返回的数组中Locale。它有点粗糙,但实际上可能有效。您还可以提取所有可用LocalesgetAvailableLocales()并搜索它们的显示名称。

回答by Arne Burmeister

I do not know ULocale, but if you mean java.util.Locale, the following code may do:

我不知道 ULocale,但如果你的意思是java.util.Locale,下面的代码可能会做:

public void setResources(String locale) {
  // validate locale
  Locale lo = parseLocale(locale);
  if (isValid(lo)) {
    System.out.println(lo.getDisplayCountry());
  } else {
    System.out.println("invalid: " + locale);
  }
}

private Locale parseLocale(String locale) {
  String[] parts = locale.split("_");
  switch (parts.length) {
    case 3: return new Locale(parts[0], parts[1], parts[2]);
    case 2: return new Locale(parts[0], parts[1]);
    case 1: return new Locale(parts[0]);
    default: throw new IllegalArgumentException("Invalid locale: " + locale);
  }
}

private boolean isValid(Locale locale) {
  try {
    return locale.getISO3Language() != null && locale.getISO3Country() != null;
  } catch (MissingResourceException e) {
    return false;
  }
}

EDIT: added validation

编辑:添加验证

回答by christophe blin

@Target({ElementType.FIELD, ElementType.METHOD})
@Retention(RUNTIME)
@Constraint(validatedBy = ValidLocaleValidator.class)
@Documented
public @interface ValidLocale {
    String message() default "{constraints.validlocale}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}   

public class ValidLocaleValidator implements ConstraintValidator<ValidLocale, String> {
    private Set<String> validLocales = new HashSet<String>();

    @Override
    public void initialize(ValidLocale constraintAnnotation) {
        Locale []locales = Locale.getAvailableLocales();
        for (java.util.Locale l : locales) {
            validLocales.add(l.toString());
        }
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {        
        return validLocales.contains(value);
    }
}

public class ValidLocaleTest {    
public static class MyBeanWithLocale {
    public static final String MSG = "not a locale";

    private String l;
    public MyBeanWithLocale(String l) {
        this.l = l;
    }
    @ValidLocale(message=MSG)
    public String getL() {
        return l;
    }
    public void setL(String l) {
        this.l = l;;
    }
}

    @Test
    public void testLocale() {
        //success
        MyBeanWithLocale b1 = new MyBeanWithLocale("fr_FR");
        Jsr303.validate(b1); //equivalent to Validation.buildDefaultValidatorFactory().getValidator().validate
        //failure
        try {
        MyBeanWithLocale b2 = new MyBeanWithLocale("FRANCE");
        Jsr303.validate(b2);//equivalent to Validation.buildDefaultValidatorFactory().getValidator().validate
        Assert.fail();
        } catch (Exception e) {
        Assert.assertEquals("[" + MyBeanWithLocale.MSG + "]", e.getCause().getMessage());
        }
    }    

}

}

回答by Aaron Digulla

commons langhas a utility method to parse and validate locale strings: LocaleUtils.toLocale(String)

commons lang有一个实用方法来解析和验证语言环境字符串:LocaleUtils.toLocale(String)

After that, you just have to check whether the variant is empty:

之后,您只需要检查变体是否为空:

Validate.isTrue( StringUtils.isBlank( locale.getVariant() ) );

回答by user1876251

use org.apache.commons.lang.LocaleUtils.toLocale(localeString).

使用org.apache.commons.lang.LocaleUtils.toLocale(localeString).

one-liner, other than catching java.lang.IllegalArgumentException.

单线,除了抓java.lang.IllegalArgumentException

回答by santiagozky

I had this problem recently. With the help from Common-lang I came up with this

我最近遇到了这个问题。在 Common-lang 的帮助下,我想出了这个

 public static Locale getValidLocale(final Locale locale) {

    Set<Locale> locales = LocaleUtils.availableLocaleSet();
    List<Locale> givenLocales = LocaleUtils.localeLookupList(locale, Locale.ENGLISH);
    for (Locale loc : givenLocales) {
        if (locales.contains(loc)) {
            return loc;
        }
    }
    return Locale.ENGLISH;

}

LocaleUtils.availableLocaleSet() returns all available locales, but it stores the list in a static variable, so it is iterated only once

LocaleUtils.availableLocaleSet() 返回所有可用的语言环境,但它将列表存储在一个静态变量中,因此它只迭代一次

LocaleUtils.localeLookupList() takes a locale and creates a list with different granularities.

LocaleUtils.localeLookupList() 获取语言环境并创建具有不同粒度的列表。

The code basically validates your locale using a more general version until english is used as fallback.

该代码基本上使用更通用的版本验证您的语言环境,直到使用英语作为后备。

回答by Jared Burrows

There are plenty of answers already but for a fast one-liner:

已经有很多答案,但要快速one-liner

Arrays.asList(Locale.getAvailableLocales()).contains(Locale.US)

In a method:

在一个方法中:

boolean isLocaleAvailable(Locale locale) {
   return Arrays.asList(Locale.getAvailableLocales()).contains(locale);
}

回答by VdeX

isAvailableLocale(Locale locale) 

Is answer to your question.

是对你问题的回答。

Example:

例子:

String key= "ms-MY";
Locale locale = new Locale.Builder().setLanguageTag(key).build();
 if (LocaleUtils.isAvailableLocale(locale))
 {
  System.out.println("Locale present");
 }

Avoid using getAvailableLocales()it will return you 155locales Its time consuming.

避免使用getAvailableLocales()它会返回155 个语言环境,这很耗时。

If possible please explore more at LocaleUtils classand Locale

如果可能,请在LocaleUtils 类Locale 中探索更多信息