0

I want to use one thread to transfer multiple files, on the client side, I just read a file then write them to the outputstream

 while ((read = dis.read(buf)) != -1) {
                    passedlen += read;
                    dos.write(buf, 0, read);
 }

but it won't stop when the inputsream(dis) has read one file,so all the file s rushed to only one outputstream which writes to one file on my serverside.

so,what can I do to receive my files one bye one through the socket inputstream?

Jens Schauder
  • 77,657
  • 34
  • 181
  • 348
kknight
  • 19
  • 1
  • 8

1 Answers1

0

There are protocols for file transfer.

Solution 1. You can reinvent your own little protocol : like storing each file length before the file content. Assuming dos is a DataOutputStream :

while ( ( file = ... ) != null ) {
  long fileSize = ...
  dos.writeLong(fileSize);

  ... write file data to dos as you did ...

}

When you read at the other end, first read the file size, then read fileSize bytes. Repeat until end of stream.

Alternative solutions

  • Use TAR : it was designed exactly for that purpose. See JTAR for java.
Nytux
  • 358
  • 1
  • 9
  • dos.write( buffer.array(), 0, Long.BYTES ); dos means what here? – kknight Mar 21 '15 at 10:40
  • @kknight He appears to means an unstated `DataOutputStream,` but if he has one of those he doesn't need the `ByteBuffer` stuff. The duplicated question has a better answer than this. – user207421 Mar 22 '15 at 03:35
  • @kknight It means write the content of `buffer.array()` to dos. The size of buffer.array() is `Long.BYTES` bytes. I assume dos is a generic OutputStream on which you can just write bytes. – Nytux Mar 22 '15 at 08:01
  • OK, the variable name `dos` probably indicates it's a DataOutputStream, so writeLong is more appropriate. – Nytux Mar 22 '15 at 08:12
  • @Nytux What do you mean 'probably'? It's your code? Isn't it? – user207421 Mar 22 '15 at 08:50
  • @EJP I'm starting from the code of kknight and his two variables dos and dis that I assumed to be of type OutputStream and InputStream. Anyway, even if they were, the best solution is to encapsulate them into DataOutputStream and DataInputStream. It avoids using ByteBuffers as I did in the first version of my post. – Nytux Mar 22 '15 at 13:20
  • @EJP thank you,the duplicated question helps.I just tried to use readFully() to work this out,but this method constrains the file length,your answer really works perfectly. – kknight Mar 22 '15 at 13:56