`
orange5458
  • 浏览: 347647 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

String编码(一) 关于String.getBytes()

 
阅读更多

1.简介

本次学习的目的是为了弄清JAVA在不同情况下对String处理方式,从而更好的解决String乱码问题。

2.获取JAVA中String的编码

代码

package com.siyuan.jdk.test;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;

public class StringGetBytes {
	
	public static void main(String[] args) throws UnsupportedEncodingException {
		String str = "I AM 中国人";
		System.out.println("str = " + str);
		System.out.println("Default byte codes of str : " + Arrays.toString(str.getBytes()));
		System.out.println("GBK codes of str : " + Arrays.toString(str.getBytes("GBK")));
		System.out.println("UTF-8 codes of str : " + Arrays.toString(str.getBytes("UTF-8")));
		System.out.println("UTF-16 codes of str : " + Arrays.toString(str.getBytes("UTF-16")));
	}
	
}

 运行结果

str = I AM 中国人
Default byte codes of str : [73, 32, 65, 77, 32, -42, -48, -71, -6, -56, -53]
GBK codes of str : [73, 32, 65, 77, 32, -42, -48, -71, -6, -56, -53]
UTF-8 codes of str : [73, 32, 65, 77, 32, -28, -72, -83, -27, -101, -67, -28, -70, -70]
UTF-16 codes of str : [-2, -1, 0, 73, 0, 32, 0, 65, 0, 77, 0, 32, 78, 45, 86, -3, 78, -70]

疑问

1)默认的getBytes()返回的编码为GBK的,而不是JAVA中的char编码方式Unicode,即UTF-16

通过跟踪String.getBytes()方法发现返回字节使用的编码为JVM的默认charset:Charset.defaultCharset(),而不是UTF-16

代码片段:

String

    public byte[] getBytes() {
	return StringCoding.encode(value, offset, count);
    }

 StringCoding

    static byte[] encode(char[] ca, int off, int len) {
	String csn = Charset.defaultCharset().name();
	try {
	    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

    public static Charset defaultCharset() {
        if (defaultCharset == null) {
	    synchronized (Charset.class) {
		java.security.PrivilegedAction pa =
		    new GetPropertyAction("file.encoding");
		String csn = (String)AccessController.doPrivileged(pa);
		Charset cs = lookup(csn);
		if (cs != null)
		    defaultCharset = cs;
                else 
		    defaultCharset = forName("UTF-8");
            }
	}
	return defaultCharset;
    }

 可通过运行参数-Dfile.encoding="UTF-8"进行修改
修改eclipse中的运行参数



运行结果

str = I AM 涓浗浜?
Default byte codes of str : [73, 32, 65, 77, 32, -28, -72, -83, -27, -101, -67, -28, -70, -70]
GBK codes of str : [73, 32, 65, 77, 32, -42, -48, -71, -6, -56, -53]
UTF-8 codes of str : [73, 32, 65, 77, 32, -28, -72, -83, -27, -101, -67, -28, -70, -70]
UTF-16 codes of str : [-2, -1, 0, 73, 0, 32, 0, 65, 0, 77, 0, 32, 78, 45, 86, -3, 78, -70]

 问题

打印str出现乱码,但是字节编码正常
原因:Console控制台的编码不是UTF-8

修改eclipse中的console控制台编码



 运行结果:

str = I AM 中国人
Default byte codes of str : [73, 32, 65, 77, 32, -28, -72, -83, -27, -101, -67, -28, -70, -70]
GBK codes of str : [73, 32, 65, 77, 32, -42, -48, -71, -6, -56, -53]
UTF-8 codes of str : [73, 32, 65, 77, 32, -28, -72, -83, -27, -101, -67, -28, -70, -70]
UTF-16 codes of str : [-2, -1, 0, 73, 0, 32, 0, 65, 0, 77, 0, 32, 78, 45, 86, -3, 78, -70]

2)UTF-16编码前面有两个字节为-2,-1

由于不同处理器对2字节处理方式不同,Big-endian(高位字节在前,低位字节在后)或Little-endian(低位字节在前,高位字节在后)编码,所以在对一串字符串进行编码是需要指明到底是Big-endian还是Little-endian,所以前面有两个字节用来保存BYTE_ORDER_MARK值

  • 大小: 85.6 KB
  • 大小: 90.5 KB
分享到:
评论

相关推荐

    C#_string_byte数组转换解析

    其它编码方式的,如System.Text.UTF8Encoding,System.Text.UnicodeEncoding class等;例如: string类型转成ASCII byte[]:("01" 转成 byte[] = new byte[]{ 0x30, 0x31}) 1 byte[] byteArray = System.Text....

    C# char[]与string byte[]与string之间的转换详解

    1、char[]与string之间的转换 //string 转换成 Char[] string str=hello; char[] arr=str.ToCharArray(); //Char[] 转换成 string string str1 = new ...//string 转换成 byte[] (字符串是用哪种编码生成的byte[]

    Java中的String类getBytes()方法详解与实例

    在本文中,我们学习了Java String类的getBytes()方法,它允许将字符串转换为字节数组,并且可以指定字符编码方式。通过实例和代码演示了使用平台默认字符编码和指定UTF-8、ISO-8859-1字符编码的情况。getBytes()方法...

    史上最全的java基础总结大全

    public static void main(String[] args) { //编码解码1:默认编码 String str1 = "你好"; byte[] buf1 = str1.getBytes();//默认解码:Unicode,四个字节 //编码解码2:指定编码 String str2 = "你好"; ...

    C#(.net)中按字节数截取字符串最后出现乱码问题的解决

    Encoding.UTF8.GetBytes采用的是utf-8编码。这样当然是乱码。尤其出现中文时候。 对这类数据处理当然要用统一的编码来处理。下面话不多说了,来一起看看详细的介绍吧 例子:1 string msg= Encoding.UTF8....

    JS实现对中文字符串进行utf-8的Base64编码的方法(使其与Java编码相同)

    本文实例讲述了JS实现对中文字符串...String encodeStr = new String(Base64.encode(sql.getBytes(UTF-8))); // 编码 System.out.println(encodeStr); 得到: c2VsZWN0IOeUqOaIt+WQjSBmcm9tIOeUqOaItw== 在Java中

    字符串各种编码转换 Scanner 、String

    此例子是一个字符串转各种编码的demo,编码格式是已经定义好的,当然你也可以扩充,使用时只需要构造它的对象然后调用对应的转换格式的方法即可,很简单的!

    struts2上传插件(中文编码冲突解决)

    解决Struts2上传时候使用UTF-8的冲突问题... * 对于请求流,使用的ISO-8859-1编码方式进行,如果发现请求内容中出现名称乱码,请使用new String(str.getBytes("ISO-8859-1"),"GBK")进行编码转换。 包里面已经含有源代码

    PDU短信发送编码程序(C#)

    byte[] resByte = System.Text.UnicodeEncoding.Unicode.GetBytes(smsg); for (int i = 0; i < resByte.Length ; i+=2) { ls = resByte[i].ToString("X2"); rs = resByte[i + 1].ToString("X2"); res = res + ...

    2020年SpringMVC面试题,看这篇就足够了

    1. 什么是SpringMVC? SpringMVC是一种基于 Java 的实现MVC设计模型的请求驱动类型的轻量级Web框架,属于Spring框架的一个...String userName = new String(request.getParamter("userName").getBytes("ISO8859-1"),"u

    jspsmartupload上传下载,已修改过源代码!

    //我将文件名getBytes()下,将GBK改成UTF-8。测试了下,貌似没问题, //突然有一次上传一文件时,发现最后几个字乱码,一直是??。在拿些文件测试, // 后来知道了是当文件名为中文奇数时,会乱码,而且还上传不了。...

    base45-java:Qr代码的base45的Java实现

    String encodedString = Base45.getEncoder().encodeToString(originalInput.getBytes());然后解码回去: byte[] decodedBytes = Base44.getDecoder().decode(encodedString);String decodedString = new String...

    excel-template-export.rar

    filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1")); //将文件输出到页面 ServletOutputStream out = response.getOutputStream(); bis = new BufferedInputStream(inputStream); bos = ...

    DownLoadUtil.java

    public static String getFileName(String agent, String filename) throws UnsupportedEncodingException { if (agent.contains("MSIE")) { // IE浏览器 filename = URLEncoder.encode...

    java 爬网 程序 示例

    // keyword = new String(param.getBytes("gb2312"), "ISO-8859-1"); // } catch (UnsupportedEncodingException e1) { // // TODO Auto-generated catch block // e1.printStackTrace(); // } // ...

    ganymed-ssh2-build210.jar java远程访问linux服务器操作、上传下载文件

    public static byte[] getBytes(String filePath) { byte[] buffer = null; try { File file = new File(filePath); FileInputStream fis = new FileInputStream(file); ByteArrayOutputStream ...

    c#中文gbk编码查询示例代码

    代码如下:private void button_Inquriy_Click(object sender, EventArgs e) { if ... byte[] bytes = Encoding.GetEncoding(“GB2312”).GetBytes(strInquiry); String strResult = String.Empty; foreach (b

    短信发送代码

    (length % 2 == 0))//不是偶数则加上F,与最后一位互换 { result += 'F'; result += value[length - 1]; } return result; } /**/ /// /// 短信内容编码 /// /// <param name="value"></param> /// ...

    全文修改编码

    全文修改编码,request.setCharacterEncoding("gb2312"); 或者单个修改 out.print("用户名:"+new String(request.getParameter("name").getBytes("iso-8859-1"),"gb2312")+" ");

    c# http post get

    //默认编码方式,根据需要设置其他类型 client.OpenRead("http://www.baidu.com");//普通get请求 MessageBox.Show(client.RespHtml);//获取返回的网页源代码 client.DownloadFile(...

Global site tag (gtag.js) - Google Analytics