leviem1
leviem1

Reputation: 411

Java Sockets - Data duplicated on last write

I have the following code that I am using to send a file to a client:

private void sendFile(Socket client) throws Exception {
        byte[] data = new byte[4096];
        DataOutputStream dos = new DataOutputStream(client.getOutputStream());
        FileInputStream fis = new FileInputStream("test.txt");

        while (fis.read(data, 0, data.length) != -1) {
            dos.write(data);
        }

        fis.close();
        dos.close();
}

The problem that I'm finding is that the file sizes are different after transfer. Upon further investigation, I discovered that the files were being duplicated on the last dos.write(data).

Example:

Original File:

Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Cras dictum diam neque, eu dictum sem efficitur ut.
Ut eu hendrerit risus.
In dapibus vel lectus at egestas.

Transferred File:

Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Cras dictum diam neque, eu dictum sem efficitur ut.
Ut eu hendrerit risus.
In dapibus vel lectus at egestas.
Ut eu hendrerit risus.
In dapib

I'm at wit's end here and I've already looked at hundreds of examples trying to fix this. I've tried dos.flush(), changing the read to dos.read(data), and changing the while loop condition. I'm expecting to transfer very large files so I don't want to load a file all at once.

EDIT:

I have been using both telnet and netcat from the command line for testing the download.

Upvotes: 0

Views: 111

Answers (1)

Scary Wombat
Scary Wombat

Reputation: 44834

see this method

https://docs.oracle.com/javase/7/docs/api/java/io/DataOutputStream.html#write(byte[],%20int,%20int)

and

https://docs.oracle.com/javase/7/docs/api/java/io/FileInputStream.html#read(byte[],%20int,%20int)

len - the maximum number of bytes read.

and returns

the total number of bytes read into the buffer

You only want to write the amount of bytes that were read previously

so

  int br = -1;
  while ((br = fis.read(data, 0, data.length)) != -1) {
        dos.write(data, 0, br);
  }

Upvotes: 1

Related Questions