【发布时间】:2015-06-07 10:40:03
【问题描述】:
我有一个服务器先发送文件大小和文件数据的情况。在客户端读取时如何区分整数值和文件数据?
服务器的相同代码(os 是缓冲的输出流):
// Construct a 1K buffer to hold bytes on their way to the socket.
byte[] mybytearray = new byte[(int) myFile.length()];
//File Size
os.write((int) myFile.length());
FileInputStream fis = null;
System.out.println("test+sendbytes");
// Copy requested file into the socket's output stream.
try {
fis = new FileInputStream(myFile);
} catch (FileNotFoundException ex) {
// Do exception handling
}
BufferedInputStream bis = new BufferedInputStream(fis);
try {
bis.read(mybytearray, 0, mybytearray.length);
os.write(mybytearray, 0, mybytearray.length);
os.flush();
os.close();
os.close();
// File sent, exit the main method
return;
} catch (IOException ex) {
// Do exception handling
}
【问题讨论】:
-
os.write((int)myFile.length())是 wrong 正如彼得劳里的回答所指出的那样。它写入一个值为myFile.length() & 0xFF的字节。此外,在os.close()之前不需要调用os.flush()。close()始终刷新任何核心 IO 类中的任何剩余数据。