ObjectInputStream给出奇怪的结果

问题描述:

这是我使用的代码。ObjectInputStream给出奇怪的结果

客户:

public static void main(String[] args) throws IOException { 
    Socket socket = new Socket("0.0.0.0", 5555); 
    ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream()); 
    FileInputStream in = new FileInputStream("C:/Documents and Settings/Owner/Desktop/Client/README.txt"); 
    byte[] b = new byte[1024]; 
    int i = 0; 
    i = in.read(b); 
    out.writeInt(i); 
    out.write(b, 0, i); 
    out.flush(); 
    i = in.read(b); 
    out.writeInt(i); 
    out.write(b, 0, i); 
    out.flush(); 
    out.close(); 
    in.close(); 
    socket.close(); 
} 

服务器:在它

public static void main(String[] args) throws IOException { 
    ServerSocket ss = new ServerSocket(5555); 
    Socket s = ss.accept(); 
    ObjectInputStream in = new ObjectInputStream(s.getInputStream()); 
    FileOutputStream fos = new FileOutputStream("C:/README.txt"); 
    int i = 0; 
    i = in.readInt(); 
    System.out.println(i); 
    byte[] bytes = new byte[i]; 
    in.read(bytes); 
    i = in.readInt(); 
    System.out.println(i); 
    byte[] bytes2 = new byte[i]; 
    in.read(bytes2); 
    fos.write(bytes); 
    fos.close(); 
    s.close(); 
    ss.close(); 
} 

readme.txt文件有〜2400个字节。当我运行这个时,服务器输出这个。

然后,它抛出一个java.lang.OutOfMemoryError。

有人可以告诉我为什么它读取1869488225而不是1024?

感谢

+0

你为什么试图读取两次数据? – Jeffrey 2012-04-26 01:23:13

+0

@Jeffrey它发送两个1024字节的不同块。 – Stripies 2012-04-26 01:24:18

+0

是的,但是如果'README.txt'中有2400字节的文本,2400 - 2048 = 352字节的未发送数据。你应该使用一个循环来发送你的数据块 – Jeffrey 2012-04-26 01:25:20

in.read(bytes); 
in.read(bytes2); 

这里被您忽略读的返回值,并假设它填补了缓冲。你应该在这里更改read()readFully(),但一般而言,你永远不应该忽略read()的结果。它可以是-1表示EOS,也可以是从1到缓冲区大小的任意数。如果您无意中指定了零长度缓冲区,则它甚至可以为零。