2016-04-24 94 views
0

在我的应用程序中,我使用套接字从客户端发送文件。另一方面,另一个客户端使用InputStream接收文件,然后使用bufferedOutputStream将文件保存在系统中。InputStream.read()在读取文件时挂起

我不知道为什么,文件没有完全传输。我认为这是因为网络过载,无论如何,我不知道如何解决它。

的发射机是:

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

尝试记录bytesReaded的值,看看它是怎么回事 – AdamSkywalker

+0

通常,建议使用调试器和检查变量值。 –

+0

我以前做过。例如,如果文件有10000个字节,它在接收到9000个字节时就会卡住。 –

回答

3

你没有说明其中filesize是从哪里来的,但也有许多问题与此代码。太多提及。全部扔掉并使用DataInputStream.readFully()。或者使用下面的复制循环,这并不需要一个缓冲文件的大小,它不能扩展的技术,假定文件大小适合的int,并增加了延迟:

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

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

+0

在你的循环中,“in”变量是一个“InputStream”? –

+0

@MMManuel当然,'out'将是'OutputStream'。我不认为这需要说明。 – EJP

+0

在每次写入事件的“计数”中不应该增加偏移量? –