Where to get “UTF-8” string literal in Java?

前端 未结 11 837
谎友^
谎友^ 2020-12-02 03:51

I\'m trying to use a constant instead of a string literal in this piece of code:

new InputStreamReader(new FileInputStream(file), \"UTF-8\")
<
相关标签:
11条回答
  • 2020-12-02 04:38

    In case this page comes up in someones web search, as of Java 1.7 you can now use java.nio.charset.StandardCharsets to get access to constant definitions of standard charsets.

    0 讨论(0)
  • 2020-12-02 04:38

    There are none (at least in the standard Java library). Character sets vary from platform to platform so there isn't a standard list of them in Java.

    There are some 3rd party libraries which contain these constants though. One of these is Guava (Google core libraries): http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/base/Charsets.html

    0 讨论(0)
  • 2020-12-02 04:42

    This constant is available (among others as: UTF-16, US-ASCII, etc.) in the class org.apache.commons.codec.CharEncoding as well.

    0 讨论(0)
  • 2020-12-02 04:43

    Now I use org.apache.commons.lang3.CharEncoding.UTF_8 constant from commons-lang.

    0 讨论(0)
  • 2020-12-02 04:47

    In Java 1.7+

    Do not use "UTF-8" string, instead use Charset type parameter:

    import java.nio.charset.StandardCharsets
    
    ...
    
    new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8);
    
    0 讨论(0)
提交回复
热议问题