【问题标题】:InputStream.read() hangs on reading a fileInputStream.read() 在读取文件时挂起
【发布时间】:2023-04-11 06:55:01
【问题描述】:

在我的应用程序中,我使用套接字从客户端发送文件。另一方面,另一个客户端使用 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);

【问题讨论】:

  • 尝试记录 bytesReaded 的值,看看进展如何
  • 通常,建议使用调试器单步执行并检查变量值。
  • 我以前做过。例如,如果文件有 10000 字节,当它收到 9000 字节时就会卡住。

标签: android sockets inputstream fileinputstream


【解决方案1】:

您没有说明filesize 的来源,但这段代码存在许多问题。太多了,就不一一赘述了。把它全部扔掉并使用DataInputStream.readFully()。或者使用以下复制循环,它不需要文件大小的缓冲区,这种技术不会缩放,假设文件大小适合int,并增加延迟:

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

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

【讨论】:

  • 在您的循环中,“in”变量将是“InputStream”?
  • @MMManuel 当然,out 将是OutputStream。我认为这不需要说明。
  • 不应该在每次写入事件的“计数”中增加偏移量吗?
  • @MMManuel 不。这是缓冲区的偏移量,而不是目标流的偏移量。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-23
  • 1970-01-01
  • 2020-06-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多