JAVA里面关于byte数组和String之间的转换问题

JAVA里面关于byte数组和String之间的转换问题
来源:考试大    2009年08月21日 13:34
JAVA里面关于byte数组和String之间的转换问题
  引自:http://soniccyj.bokee.com/6175850.html
  JAVA里面关于byte数组和String之间的转换问题
  把byte转化成string,必须经过编码。
  例如下面一个例子:
  import java.io.UnsupportedEncodingException;
  public class test{
  public static void main(String g[]) {
  String s = "12345abcd";
  byte b[] = s.getBytes();
  String t = b.toString();
  System.out.println(t);
  }
  }
  输出字符串的结果和字符串s不一样了.
  经过以下方式转码就可以正确转换了:
  public class test{
  public static void main(String g[]) {
  String s = "12345abcd";
  byte b[] = s.getBytes();
  try {
  String t = new String(b);
  System.out.print(t);
  } catch (Exception e) {
  e.printStackTrace();
  }
  }
  }
  引自:http://topic.csdn.net/t/20050404/10/3906398.html
  String str = "String";
  byte[] byte1 = str.getBytes();
  String str1 = new String(byte1);
  byte[] byte2 = str1.getBytes();
  String str2 = new String(byte2);
  System.out.println("str<<<" + str);
  System.out.println("byte1<<<" + byte1);
  System.out.println("str1<<<" + str1);
  System.out.println("byte2<<<" + byte2);
  System.out.println("str2<<<" + str2);
  -------------------------------------
  输出结果
  str<<<String
  byte1<<<[B@192d342
  str1<<<String
  byte2<<<[B@6b97fd
  str2<<<String
  想请教为什么两个byte输出的不一样呢?
  String str = "String";
  byte[] byte1 = str.getBytes();
  String str1 = new String(byte1);
  byte[] byte2 = str1.getBytes();
  ----------
  注意byte1是str得到的byte数组,而byte2是另一个字符串str1得到的数组
  他们本身也是两个对象
  直接打印实际上调用的是toString()方法,而toString()的默认实现是打印对象类型+hashCode()
  [B表示byte数组
  @表示之后的是地址
  后面跟着的是hashCode,其实就是其虚拟机地址
  所以这个结果也就是顺理成章了.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值