在Java中哪里可以获得“UTF-8”字符串文字?

本文翻译自: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-16US-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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值