`
顽石OK07
  • 浏览: 80734 次
  • 性别: Icon_minigender_2
  • 来自: 上海
社区版块
存档分类
最新评论

String.getBytes()和new String()

阅读更多

转载: http://hi.baidu.com/tianpaomian/blog/item/cb15c4317f7f8ca15edf0e3d.html

 

在Java中,String.getBytes(String decode)方法会根据指定的decode编码返回某字符串在该编码下的byte数组表示,如

byte[] b_gbk = "中".getBytes("GBK");
byte[] b_utf8 = "中".getBytes("UTF-8");
byte[] b_iso88591 = "中".getBytes("ISO8859-1");

将分别返回“中”这个汉字在GBK、UTF-8和ISO8859-1编码下的byte数组表示,此时b_gbk的长度为2,b_utf8的长度为3,b_iso88591的长度为1。

而与getBytes相对的,可以通过new String(byte[], decode)的方式来还原这个“中”字时,这个new String(byte[], decode)实际是使用decode指定的编码来将byte[]解析成字符串。

String s_gbk = new String(b_gbk,"GBK");
String s_utf8 = new String(b_utf8,"UTF-8");
String s_iso88591 = new String(b_iso88591,"ISO8859-1");

通过打印s_gbk、s_utf8和s_iso88591,会发现,s_gbk和s_utf8都是“中”,而只有s_iso88591是一个不认识 的字符,为什么使用ISO8859-1编码再组合之后,无法还原“中”字呢,其实原因很简单,因为ISO8859-1编码的编码表中,根本就没有包含汉字 字符,当然也就无法通过"中".getBytes("ISO8859-1");来得到正确的“中”字在ISO8859-1中的编码值了,所以再通过new String()来还原就无从谈起了。

因此,通过String.getBytes(String decode)方法来得到byte[]时,一定要确定decode的编码表中确实存在String表示的码值,这样得到的byte[]数组才能正确被还原。

有时候,为了让中文字符适应某些特殊要求(如http header头要求其内容必须为iso8859-1编码),可能会通过将中文字符按照字节方式来编码的情况,如

String s_iso88591 = new String("中".getBytes("UTF-8"),"ISO8859-1"),这样得到的s_iso8859-1字符串实际是三个在 ISO8859-1中的字符,在将这些字符传递到目的地后,目的地程序再通过相反的方式String s_utf8 = new String(s_iso88591.getBytes("ISO8859-1"),"UTF-8")来得到正确的中文汉字“中”。这样就既保证了遵守协 议规定、也支持中文。

分享到:
评论
1 楼 abc382410124 2013-03-19  
不错呀 学习了

相关推荐

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

    string str1 = new string(arr); 2、byte[]与string之间的转化 string str = 你好,hello; byte[] bytes; //byte[] 转换成 string bytes = Encoding.UTF8.GetBytes(str); //string 转换成 byte[] (字符串是用哪种...

    C#_string_byte数组转换解析

    string类型转成ASCII byte[]:("01" 转成 byte[] = new byte[]{ 0x30, 0x31}) 1 byte[] byteArray = System.Text.Encoding.ASCII.GetBytes ( str ); ASCII byte[] 转成string:(byte[] = new byte[]{ 0x30, 0x31...

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

    String str3 = new String(buf3,"ISO8859-1");//错误解码 //编码解码4:错误编码正确解码 String str4 = "你好"; byte[] buf4 = str4.getBytes("ISO8859-1");//错误编码 String str4 = new String(buf4,"GBK")...

    IO流的使用,自己的心得

    byte writeStringToBytes[] = writeString.getBytes(); byte temp[] = new byte[tempLength]; //需要几次写入 if(writeStringToBytes.length%tempLength==0) each = writeStringToBytes.length/...

    Des加密解密C#源码

    Des加密解密C#源码,很实用 byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8)); byte[] rgbIV = Encoding.ASCII.GetBytes(kesVector);... return Convert.ToBase64String(mStream.ToArray());

    加密解密类DESEncrypt.cs

    public static string Encrypt(string Text,string sKey) { DESCryptoServiceProvider des = new DESCryptoServiceProvider(); byte[] inputByteArray; inputByteArray=Encoding.Default.GetBytes...

    java 小程序 课程设计 java

    String(request.getParameter("subject").getBytes("ISO-8859-1")); String str_content=new String(request.getParameter("content").getBytes("ISO-8859-1")); Properties props=new Properties(); props.put(...

    C#加密JAVA解密

    public static string Encode(string data) { byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64); byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64); ...

    MD5加密解密

    public string EnCode(string data) { byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64); byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64); DESCryptoServiceProvider ...

    Struts Updownload 源码

    this.fileName = new String(fileName.getBytes("ISO-8859-1"),"UTF-8"); } public String getContentDisposition() { return contentDisposition; } public void setContentDisposition(String ...

    java初学者必读

    newstring=new String(s.getBytes("ISO8859_1"),"gb2312"); return newstring; } catch(UnsupportedEncodingException e) { return s; } } public static String ChineseToUnicode(String s){ try{ if(s==...

    AES加密工具类

    IvParameterSpec zeroIv = new IvParameterSpec(VIPARA.getBytes()); SecretKeySpec key = new SecretKeySpec(dataPassword.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); ...

    一个完整可用的证书签名(验签),加密(解密)java源码

    System.err.println("私钥签名——公钥验证签名"); // 产生签名 String sign = CertificateUtils.signToBase... String outputStr = new String(decrypt,"utf-8"); System.out.println("解密后:" + outputStr);

    C#-DES_SAME_JAVA-DES.zip

    hexRetSB.append(hexString.length() == 1 ? 0 : "").append(hexString); } return hexRetSB.toString(); } catch (Exception e) { throw new Exception("DES加密发生错误", e); } } public ...

    C#聊天程序

    string svrlog = string.Format("[系统消息]用户 {0} 在 {1} 已断开... 当前在线人数: {2}\r\n\r\n", obj, DateTime.Now, _transmit_tb.Count); Console.WriteLine(svrlog); //向所有客户机发送系统消息 foreach...

    C# 中实现短信发送的类

    public static int SendSMS(string Number, string Message) { int returnValue = 0; IntPtr smsHandle = new IntPtr(0); // Set address structure byte[] smsatAddressType = BitConverter.GetBytes(SMSAT_...

    C#文件夹加密有源代码!

    ublic static void F加密UTF8文件(string sInputFilename, string sOutputFilename, string sKey) { FileStream fsInput = new FileStream(sInputFilename, FileMode.Open, FileAccess.Read); FileStream ...

    commons-codec-1.14.jar

    String originalString = new String(original); return originalString; } catch (Exception e) { System.out.println(e.toString()); return null; } } catch (Exception ex) { System.out.println...

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

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

    C# 字符串string和内存流MemoryStream及比特数组byte[]之间相互转换

    定义string变量为str,内存流变量为ms,比特数组为bt ... 代码如下:(1)MemoryStream ms=new MemoryStream(System.Text.Encoding.Default.GetBytes(“字符串”)); (2)MemoryStream ms=new MemoryStream(Convert.Fro

Global site tag (gtag.js) - Google Analytics