Good day to all. The computer is running a server. The client (Android application) joins it and sends a large binary file (the weight of the file is 2934822 bytes). Here is the code to send the file to the server:

this.socket_out = this.socket.getOutputStream(); ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream(); FileInputStream mFileInputStream = new FileInputStream(mFile); while (true) { byte[] i1 = new byte[65536]; int i2 = mFileInputStream.read(i1, 0, 65536); Log.v("", "read=" + i2); if (i2 < 0) { mByteArrayOutputStream.close(); mFileInputStream.close(); break; } else { mByteArrayOutputStream.write(i1, 0, i2); mByteArrayOutputStream.flush(); } } mFile.delete(); byte[] i1 = mByteArrayOutputStream.toByteArray(); Log.v("", "sent=" + i1.length); this.socket_out.write(i1); this.socket_out.flush(); 

And application logs:

read = 65536

read = 65536

...

read = 65536

read = 51238

sent = 2934822

Here is the code to get the file on the server:

 this.in = new DataInputStream(this.socket.getInputStream()); while ( byte[] i1 = new byte[65536]; int i2 = this.in.read(i1, 0, 65536); if (i2 > -1) { System.out.print(i2); ... } else { break; } } 

And standard output:

12974 1440 1440 11520 1440 1440 1440 7200 1440 1440 1440 1440 1440 1440 1440 1440 1440 1440 1440 1440 1440 1440 1440 1440 1440 1440 1440 1440 1440 1440 1440 1440 1440 1440 1440 1440 1440 1440 1440 1440 1440 1440 1440 1440 1440 1440 1440 1440 1440 1440 1440 1440 1440 1440 1440 1440 1440 1440 17280 ...

Why DataInputStream does not immediately read 65536 (2 ^ 16) bytes, but reads 1440, 7200, 12974 ..? How do I force b to read into array b as much as I specified in the len parameter of the DataInputStream.read(byte[] b, int off, int len) method DataInputStream.read(byte[] b, int off, int len) ?

  • in general, the DataInputStream has readFully methods that deduct how much is said or throw EOF if the stream ends earlier. Also, take out the creation of the buffer for the cycle, it can be reused. - zRrr

1 answer 1

An excerpt from the code to use the DataInputStream.readFully method:

 this.in = new DataInputStream(this.socket.getInputStream()); final byte[] i1 = new byte[65536]; while ( int i2 =in.readFully(i1); if (i2 > -1) { System.out.print(i2); ///... } else { break; } }