本文翻译自:Where to get “UTF-8” string literal in Java?
I'm trying to use a constant instead of a string literal in this piece of code: 我试图在这段代码中使用常量而不是字符串文字:
new InputStreamReader(new FileInputStream(file), "UTF-8")
"UTF-8"
appears in the code rather often, and would be much better to refer to some static final
variable instead. "UTF-8"
经常出现在代码中,而且更好地引用一些static final
变量。 Do you know where I can find such a variable in JDK? 你知道我在JDK哪里可以找到这样一个变量吗?
BTW, on a second thought, such constants are bad design: Public Static Literals ... Are Not a Solution for Data Duplication 顺便说一句,第二个想法,这样的常量是糟糕的设计: 公共静态文字...不是数据复制的解决方案
#1楼
参考:https://stackoom.com/question/S6Xy/在Java中哪里可以获得-UTF-字符串文字
#2楼
现在我使用来自commons-lang的 org.apache.commons.lang3.CharEncoding.UTF_8
常量。
#3楼
这个常量在类org.apache.commons.codec.CharEncoding
中也可用(其中包括: UTF-16
, US-ASCII
等)。
#4楼
如果此页面出现在某些Web搜索中,从Java 1.7开始,您现在可以使用java.nio.charset.StandardCharsets来访问标准字符集的常量定义。
#5楼
In Java 1.7+, java.nio.charset.StandardCharsets defines constants for Charset
including UTF_8
. 在Java 1.7+中, java.nio.charset.StandardCharsets定义了Charset
常量,包括UTF_8
。
import java.nio.charset.StandardCharsets;
...
StandardCharsets.UTF_8.name();
For Android: minSdk 19 对于Android:minSdk 19
#6楼
If you are using OkHttp for Java/Android you can use the following constant: 如果您使用OkHttp for Java / Android,您可以使用以下常量:
import com.squareup.okhttp.internal.Util;
Util.UTF_8; // Charset
Util.UTF_8.name(); // String