简体   繁体   English

InputStream.read()在读取文件时挂起

[英]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. 另一方面,另一个客户端使用InputStream接收文件,然后bufferedOutputStream将文件保存在系统中。

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. 您没有说明filesize来自何处,但此代码存在许多问题。 Too many to mention. 太多了。 Throw it all away and use DataInputStream.readFully() . 扔掉它并使用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: 或者使用以下复制循环,它不需要文件大小的缓冲区,一种不扩展的技术,假设文件大小适合int ,并增加延迟:

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. 如果您通过相同的连接发送多个文件,它会变得更复杂,但您没有说明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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