java send file using sockets

前端 未结 3 665
长情又很酷
长情又很酷 2020-12-28 11:08

I am trying to send a file from one computer to another using Java. I have written the code below, it works fine if both sender and receiver are started in the same computer

3条回答
  •  抹茶落季
    2020-12-28 11:34

    On the client side you write up to count bytes and send them:

    while ((count = in.read(buffer)) > 0) {
      out.write(buffer, 0, count);
    

    on the server side you read up to count bytes - but then you write the whole buffer to file!

    while((count=in.read(buffer)) > 0){
      fos.write(buffer);
    

    Just change it to:

    fos.write(buffer, 0, count);
    

    and you'll be on the safe side. BTW your program has another small bug: read() can return 0 which doesn't mean InputStream ended. Use >= instead:

    count = in.read(buffer)) >= 0
    

    Have you considered IOUtils.copy(InputStream, OutputStream) from Apache Commons? It would reduce your whole while loops to:

    OutputStream out = socket.getOutputStream();
    InputStream in = new FileInputStream(myFile);
    IOUtils.copy(in, out);
    socket.close();
    

    Less code to write, less code to test. And buffering is done internally.

提交回复
热议问题