比如:声明一个1024 字节的数组 ,传入一个Long 类型的数(占位8字节),如果我只读8个字节,会是什么情况呢?
有个例子:
import java.net.*;
import java.io.*;public class TestUDPServer{
public static void main(String[] args) throws Exception{
byte buf[] = new byte[1024];
DatagramSocket ds = new DatagramSocket (5678);
DatagramPacket dp = new DatagramPacket(buf,buf.length);
 
ds.receive(dp);
  ByteArrayInputStream bis = new ByteArrayInputStream(buf);
  //ByteArrayInputStream bis = new ByteArrayInputStream(buf,0,dp.getLength());结果为0
  DataInputStream  dis = new DataInputStream(bis);
  long n = dis.readLong();
System.out.println(n);

ds.close(); 
}

} 注释部分的写法结果为0 ,所以想了解下数组进行写和读的时候,是什么样的呢?

解决方案 »

  1.   

    当收到的字节数>=8时,new ByteArrayInputStream(buf)和new ByteArrayInputStream(buf,0,dp.getLength())是一样的。因为你后面只有一次readLong()。
      

  2.   

    楼主看看ByteArrayInputStream的源码,
    看看那个注释的构造函数中,是否有数组拷贝的代码。
    我理解,
    那个注释的构造函数中,会新生成一个数组做缓冲区。与参数不是同一个缓冲区。