MM Manuel MM Manuel - 1 year ago 115
Android Question hangs on reading a file

In my app, i'm sending a file from a client, using sockets. On the other side, another client receive the file using InputStream and then bufferedOutputStream save the file in the system.

I don´t know why, the file isn´t utterly transmited. I think this is because of network overload, anyway, i don´t know how to solve it.

Transmiter is:

Log.d(TAG,"Reading...");, 0, byteArrayFile.length);
Log.d(TAG, "Sending...");


Receiver is:

bufferedOutputStream=new BufferedOutputStream(new FileOutputStream(file));
byteArray=new byte[fileSize];

int currentOffset = 0;

bytesReaded =,0,byteArray.length);

do {
bytesReaded =, currentOffset, (byteArray.length-currentOffset));
if(bytesReaded >= 0){ currentOffset += bytesLeidos;
} while(bytesReaded > -1 && currentOffset!=fileSize);


Answer Source

You don't state where filesize came from, but there are numerous problems with this code. Too many to mention. Throw it all away and use DataInputStream.readFully(). Or use the following copy loop, which doesn't require a buffer the size of the file, a technique which does not scale, assumes that th file size fits into an int, and adds latency:

byte[] buffer = new byte[8192];
int count;
while ((count = > 0)
    out.write(buffer, 0, count);

Use this at both ends. If you're sending multiple files via the same connection it gets more complex, but you haven't stated that.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download