When using Java socket to transfer a file, I set byte[] BUFFER = new byte[1024 * 8]
, and using objectInputStream.read(BUFFER, 0, BUFFER.length)
to receive file stream, but the return value of objectInputStream.read(BUFFER, 0, BUFFER.length)
is always 1024, Why would it be 1024
not 1024 * 8
.
the BUFFER length is 1024 * 8
but len is 1024.
The reason read
returns at most 1024 is because an ObjectInputStream
internally uses a buffer of 1024 bytes (though this is an implementation detail, so it might be different in different versions or distributions of Java). A read
is not required to return the requested number of bytes, so an ObjectInputStream
will return either what is available in its current buffer, or request 1024 bytes from its upstream input stream and return that.
However, as I also mentioned in the comments, judging by the fragment of code you show in your question, you should probably not be using an ObjectInputStream
at all. You're transferring binary data obtained with read
, which means you're not using Java serialization in the code shown. Maybe you should switch to using normal input and output streams instead (that said, maybe you do use serialization at an earlier point, though combining serialization and normal binary transfer in a single stream is generally odd to do).