繁体   English   中英

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

[英]InputStream.read() hangs on reading a file

在我的应用程序中,我正在使用套接字从客户端发送文件。 另一方面,另一个客户端使用InputStream接收文件,然后bufferedOutputStream将文件保存在系统中。

我不知道为什么,这个文件并没有彻底传播。 我认为这是因为网络过载,无论如何,我不知道如何解决它。

发射器是:

Log.d(TAG,"Reading...");
                bufferedInputStream.read(byteArrayFile, 0, byteArrayFile.length);
                Log.d(TAG, "Sending...");
                bufferedOutputStream.write(byteArrayFile,0,byteArrayFile.length);

bufferedOutputStream.flush();

接收者是:

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

您没有说明filesize来自何处,但此代码存在许多问题。 太多了。 扔掉它并使用DataInputStream.readFully() 或者使用以下复制循环,它不需要文件大小的缓冲区,一种不扩展的技术,假设文件大小适合int ,并增加延迟:

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

在两端使用它。 如果您通过相同的连接发送多个文件,它会变得更复杂,但您没有说明。

暂无
暂无

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

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