关于byte[]与String的问题

becloud 2010-05-26 08:10:39

ByteArrayOutputStream baos=new ByteArrayOutputStream();
DataOutputStream dos=new DataOutputStream(baos);
dos.writeByte(2);
dos.writeByte(3);
dos.writeByte(0x83);

String data=baos.toString();
byte[] buf=baos.toByteArray();

ByteArrayInputStream bais1=new ByteArrayInputStream(data.getBytes());
DataInputStream dis1=new DataInputStream(bais1);
System.out.println(dis1.readByte());
System.out.println(dis1.readByte());
System.out.println(dis1.readUnsignedByte());
System.out.println("------------------------------------");
ByteArrayInputStream bais2=new ByteArrayInputStream(buf);
DataInputStream dis2=new DataInputStream(bais2);
System.out.println(dis2.readByte());
System.out.println(dis2.readByte());
System.out.println(dis2.readUnsignedByte());


打印结果:
2
3
239
------------------------------------
2
3
131


问题:为什么这2个打印结果不一样呢?baos.toString().getBytes()和baos.toByteArray()难道不一样?

请教各位大虾们。。。
...全文
130 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
becloud 2010-05-27
  • 打赏
  • 举报
回复

学习了,非常感谢各位朋友的帮忙
czmchen 2010-05-27
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 lifeng_2009 的回复:]

楼上两位说的很全了
[/Quote]

占个茅坑,呵呵
BearKin 2010-05-27
  • 打赏
  • 举报
回复
学习 受教育~
lodachi 2010-05-27
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 lifeng_2009 的回复:]

楼上两位说的很全了
[/Quote]同意
生活 2010-05-27
  • 打赏
  • 举报
回复
楼上两位说的很全了
dracularking 2010-05-26
  • 打赏
  • 举报
回复
这个原因应该是某些码值在某些字符集下编解码过程非一一映射导致

某些默认系统编码比如GBK,在decoding时,即baos.toString(),会出现malformed-input和unmappable-character sequences被系统默认串替代的情况;在encoding时,即data.getBytes(),也会出现在默认字符集中无法被编码的串,这时候结果是未定的。

验证一下,替换 dos.writeByte(0x83) => dos.writeByte(0x7f) 结果则是一样的 都是127

由此可见。

hq1305018 2010-05-26
  • 打赏
  • 举报
回复
ByteArrayOutputStream.toString()方法会使用本地的字符集进行编码.
String.getBytes()也同样会使用本地的字符集编码.

String data=baos.toString();这句改为 String data=baos.toString("ISO-8859-1");
data.getBytes();这句改为 data.getBytes("ISO-8859-1");
再执行程序结果就一样了.

具体的API说明请参照下边的URL
http://java.sun.com/javase/6/docs/api/java/io/ByteArrayOutputStream.html#toString()

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧