本文首发于个人微信公众号《andyqian》,期待你的关注!
前言
今天我们以String类中的getBytes()方法为例,来看一看JDK源码,getBytes()方法在帮助文档中是 这样写的:
Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.
意思是:使用平台的默认字符集将此 String 编码为 byte 序列,并将结果存储到一个新的 byte 数组中。
恩,那我们就来对不同平台的默认字符集这个问题。一探究竟。
初探源码
- 首先我们进入getBytes()源码中:
public byte[] getBytes() {
return StringCoding.encode(value, 0, value.length);
}
该方法中直接返回,StringCoding.encode(value,0,value.length),那就再点击进去看看。代码如下:
static byte[] encode(char[] ca, int off, int len) {
String csn = Charset.defaultCharset().name();
try {
// use charset name encode() variant which provides caching.
return encode(csn, ca, off, len);
} catch (UnsupportedEncodingException x) {
warnUnsupportedCharset(csn);
}
try {
return encode("ISO-8859-1", ca, off, len);
} catch (UnsupportedEncodingException x) {
// If this code is hit during VM initialization, MessageUtils is
// the only way we will be able to get any kind of error message.
MessageUtils.err("ISO-8859-1 charset not available: "
+ x.toString());
// If we can not find ISO-8859-1 (a required encoding) then things
// are seriously wrong with the installation.
System.exit(1);
return null;
}
}
在这里,我们看到了,在上述方法中,通过 Charset.defaultCharset().getName() 获取系统默认的字符集。那我们就再点击进去看看,代码如下: