jdk太神奇了
- 我们不再需要自行定义字符集常量。 直接调用java.nio.charset包下的 StandardCharsets
类,指定对应的字符集即可。以前发现了apache的FileUtils包里面有几个这样的常量,还沾沾自喜,
- 现在才发现jdk已经为我们提供了这些字符编码的静态常量,不得不说jdk太神奇了
StandardCharsets 源码
package java.nio.charset; /** * Constant definitions for the standard {@link Charset Charsets}. These * charsets are guaranteed to be available on every implementation of the Java * platform. * * @see <a href="Charset#standard">Standard Charsets</a> * @since 1.7 */ public final class StandardCharsets { private StandardCharsets() { throw new AssertionError("No java.nio.charset.StandardCharsets instances for you!"); } /** * Seven-bit ASCII, a.k.a. ISO646-US, a.k.a. the Basic Latin block of the * Unicode character set */ public static final Charset US_ASCII = Charset.forName("US-ASCII"); /** * ISO Latin Alphabet No. 1, a.k.a. ISO-LATIN-1 */ public static final Charset ISO_8859_1 = Charset.forName("ISO-8859-1"); /** * Eight-bit UCS Transformation Format */ public static final Charset UTF_8 = Charset.forName("UTF-8"); /** * Sixteen-bit UCS Transformation Format, big-endian byte order */ public static final Charset UTF_16BE = Charset.forName("UTF-16BE"); /** * Sixteen-bit UCS Transformation Format, little-endian byte order */ public static final Charset UTF_16LE = Charset.forName("UTF-16LE"); /** * Sixteen-bit UCS Transformation Format, byte order identified by an * optional byte-order mark */ public static final Charset UTF_16 = Charset.forName("UTF-16"); }
怎么使用
非常简单
@Test public void testUTF8() { System.err.println(StandardCharsets.UTF_8.name()); //UTF-8 }
这些自己更放心啦。