String的getBytes()默认编码问题

通过分析发现,file.encoding与文件编码和编译环境无关,只与运行环境有关。Tomcat在启动时根据操作系统设定file.encoding为GBK。在Windows简体中文环境下,可通过修改catalina.bat将file.encoding设置为UTF-8,重启Tomcat后,getBytes()将按UTF-8编码处理。
摘要由CSDN通过智能技术生成
我们学习java基础的时候.我们都知道在main方法中String的getBytes()方法如果不指定编码格式,默认是UTF-8的方法进行的编码.我们一直认为默认的编码格式就是UTF-8.直到我们学习了javaWeb.在Servlet中.我们通过getBytes()获取的是按照GBK进行编码的.至此我们就有了疑惑.这个getBytes()方法到底是怎么选择默认编码的.我们带着疑惑,去翻一下String的源代码.
[AppleScript] 纯文本查看 复制代码
?
1
2
3
public byte[] getBytes() {
        return StringCoding.encode(value, 0, value.length);
    }
继续跟进StringCoding的encode方法
[AppleScript] 纯文本查看 复制代码
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
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;
        }
    }
从以上源码中可以看出是通过
[AppleScript] 纯文本查看 复制代码
?
1
String csn = Charset.defaultCharset().name();
来获取默认编码方式的.我们继续跟进.查看Charset的defaultCharSet()方法.
[AppleScript] 纯文本查看 复制代码
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
public static Charset defaultCharset() {
        if (defaultCharset == null) {
            synchronized (Charset.class) {
                String csn = AccessController.doPrivileged(
                    new GetPropertyAction("file.encoding"));
                Charset cs = lookup(csn);
                if (cs != null)
                    defaultCharset = cs;
                else
                    defaultCharset </
  • 5
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值