Discuss / Java / 错误指正

错误指正

Topic source

本节原文代码:

byte[] b1 = "Hello".getBytes(); // 按ISO8859-1编码转换,不推荐

错误说明:此处注释应该为,按当前操作系统环境确定的编码转换

String源码:

/** * Encodes this {@code String} into a sequence of bytes using the * platform's default charset, storing the result into a new byte array. * * <p> The behavior of this method when this string cannot be encoded in * the default charset is unspecified.  The {@link * java.nio.charset.CharsetEncoder} class should be used when more control * over the encoding process is required. * * @return  The resultant byte array * * @since      1.1 */public byte[] getBytes() {    return StringCoding.encode(coder(), value);}


源码注释中说,如果```getBytes()```方法没有指定编码,会使用平台默认的编码,在encode方法中使用了Charset.defaultCharset()方法,该方法的注释说会使用当前操作系统默认编码,经在代码验证,我的系统是window10的中文环境系统,会打印GBK,我测试代码如下:

public static void main(String[] args) {    System.out.println(Charset.defaultCharset());}

廖雪峰

#2 Created at ... [Delete] [Delete and Lock User]

?

我的环境是 Windows 10 20H2 v19342 + Java 14,Charset.defaultCharset() 输出 UTF-8。


  • 1

Reply