Java multiple file transfer over socket

You are reading the socket until read() returns -1. This is the end-of-stream condition (EOS). EOS happens when the peer closes the connection. Not when it finishes writing one file.

You need to send the file size ahead of each file. You’re already doing a similar thing with the file count. Then make sure you read exactly that many bytes for that file:

String filename = dis.readUTF();
long fileSize = dis.readLong();
FileOutputStream fos = new FileOutputStream(filename);
while (fileSize > 0 && (n =, 0, (int)Math.min(buf.length, fileSize))) != -1)
  fileSize -= n;

You can enclose all this in a loop that terminates when readUTF() throws EOFException. Conversely of course you have to call writeUTF(filename) and writeLong(filesize) at the sender, before sending the data.

Leave a Comment