MM Manuel
MM Manuel

Reputation: 385

InputStream.read() 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...");
                bufferedInputStream.read(byteArrayFile, 0, byteArrayFile.length);
                Log.d(TAG, "Sending...");
                bufferedOutputStream.write(byteArrayFile,0,byteArrayFile.length);

bufferedOutputStream.flush();

Receiver is:

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

                            int currentOffset = 0;

                            bytesReaded = bufferedInputStream.read(byteArray,0,byteArray.length);
                            currentOffset=bytesReaded;

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


                            bufferedOutputStream.write(byteArray,0,currentOffset);

Upvotes: 1

Views: 1982

Answers (1)

user207421
user207421

Reputation: 310860

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 the file size fits into an int, and adds latency:

byte[] buffer = new byte[8192];
int count;
while ((count = in.read(buffer)) > 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.

Upvotes: 3

Related Questions