1
這是我使用的代碼。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?
感謝
你爲什麼試圖讀取兩次數據? – Jeffrey 2012-04-26 01:23:13
@Jeffrey它發送兩個1024字節的不同塊。 – Stripies 2012-04-26 01:24:18
是的,但是如果'README.txt'中有2400字節的文本,2400 - 2048 = 352字節的未發送數據。你應該使用一個循環來發送你的數據塊 – Jeffrey 2012-04-26 01:25:20