ByteArrayOutputStream的toByteArray();方法

shaluoshuangshu 2010-07-10 11:51:59

import java.io.ByteArrayOutputStream;

public class TestByteArrayOutputStream{
public static void main(String args[]){
ByteArrayOutputStream b = new ByteArrayOutputStream();
b.write(3);
b.write(4);
b.write(5);
byte[] data = b.toByteArray();
int row=data.length;
for(int i=0;i<row;i++){
System.out.println(data[i]);
}
}
}


初学者,请问,toByteArray();返回的是一个字节数组,现在写了3个整数进去,而一个整数占4个字节,应该
data的长度是12才是,怎么是3?还能输出整数出来?
...全文
724 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
「已注销」 2010-07-11
  • 打赏
  • 举报
回复
java.io.OutputStream.write(int b)
throws IOException将指定的字节写入此输出流。write 的常规协定是:向输出流写入一个字节。要写入的字节是参数 b 的八个低位。b 的 24 个高位将被忽略。
龙四 2010-07-10
  • 打赏
  • 举报
回复
public void write(int b)将指定的字节写入此字节数组输出流。

你可以试试将Integer.MAX_VALUE写进去看看
Headsen 2010-07-10
  • 打赏
  • 举报
回复

public static void main(String[] args) {
ByteArrayOutputStream o = new ByteArrayOutputStream();
o.write(128);
o.write(1000);
byte d[] = o.toByteArray();
System.out.println(d[0]); //打印-128 只写入一个字节。
System.out.println(d[1]); //打印-24 只写入一个字节。
}
shaluoshuangshu 2010-07-10
  • 打赏
  • 举报
回复
[Quote=引用 8 楼 lacus87 的回复:]
API文档
[/Quote]
看了ByteArrayOutputStream的源代码,是这样的;

public synchronized void write(int b) {
int newcount = count + 1;
if (newcount > buf.length) {
buf = Arrays.copyOf(buf, Math.max(buf.length << 1, newcount));
}
buf[count] = (byte)b;
//如果我写的整数超过了byte的表示范围,后面的值就会被截去,这样保存或者
//得到的值就不准确,api上怎么不说啊?还是我理解错了?
count = newcount;
}

lacus87 2010-07-10
  • 打赏
  • 举报
回复
API文档
shaluoshuangshu 2010-07-10
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 yuanchengjun 的回复:]
看javadoc,write(int)只写1个字节。
[/Quote]
什么是javadoc?
yuanchengjun 2010-07-10
  • 打赏
  • 举报
回复
看javadoc,write(int)只写1个字节。
xtuxucj 2010-07-10
  • 打赏
  • 举报
回复
建议你看看DataOutputStream的源代码,可以看到怎样写一个Int型的。

public final void writeInt(int v) throws IOException {
out.write((v >>> 24) & 0xFF);
out.write((v >>> 16) & 0xFF);
out.write((v >>> 8) & 0xFF);
out.write((v >>> 0) & 0xFF);
incCount(4);
}
xtuxucj 2010-07-10
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 ticmy 的回复:]

public void write(int b)将指定的字节写入此字节数组输出流。

你可以试试将Integer.MAX_VALUE写进去看看
[/Quote]
搞错了,是这个
xtuxucj 2010-07-10
  • 打赏
  • 举报
回复
[Quote=引用楼主 shaluoshuangshu 的回复:]
Java code

import java.io.ByteArrayOutputStream;

public class TestByteArrayOutputStream{
public static void main(String args[]){
ByteArrayOutputStream b = new ByteArrayOutputStream()……
[/Quote]
就是这个了
person_java 2010-07-10
  • 打赏
  • 举报
回复
data长度是你的数组的长度啊,当然是3了!

62,614

社区成员

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

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