简体   繁体   中英

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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM