-3

I don't understand why create byte array in loop and copy it.If I don't create array in loop, code won't work.please explain to me

ObjectOutputStream outt = new ObjectOutputStream(socket.getOutputStream());
InputStream f=new FileInputStream(path);
byte[] buffer=new byte[10000];
int n;
while ((n=f.read(buffer))>0)
{
    byte[] tmpBuff = new byte[10000];
    System.arraycopy(buffer, 0, tmpBuff, 0, n);
    total_length += n;
    outt.writeObject(new MyObject(tmpBuff));
}
f.close();
  • 4
    This code doesn't make much sense t me. What are you trying to achieve? What is MyObject supposed to represent? – JB Nizet Mar 23 '16 at 18:56

1 Answers1

1

It appears you are writing to an ObjectOutputStream, writing blocks of 10,000. Note: you are assuming your file is always an exact multiple of 10,000 bytes.

When you write to an ObjectOutputStream it keeps track of any objects it has already written. This means if you were to write buffer repeatedly, it would only send it once. One workaround is to take a copy, although clone() would be simpler.

A better solution would be to either

  • use reset() on the ObjectOutputStream, so you can send the same buffer more than once.
  • Using DataOutputStream instead as you are transferring data not Objects.
  • only write as many bytes as you read. This way you can handle files which are not exactly a multiple of 10,000 bytes.
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130