2013-05-15 66 views
0

我試圖製作一個Android應用程序,它發送一個.txt文件到我的電腦上的Windows窗體應用程序。問題是沒有發送整個文件(我無法確定問題是發送方還是接收方)。我只從.txt文件中間的某個地方向接收方發送一個隨機部分。我究竟做錯了什麼?奇怪的是,它已經完成了幾次,但現在我永遠不會得到文件的開始或結束。從Android發送/接收.txt文件到PC,不是發送整個文件

Android應用程序是用Java編寫的,而Windows Forms應用程序是用C#編寫的。文件路徑是我的文件的名稱。這裏有什麼問題?

代碼Android應用(發送文件)

//create new byte array with the same length as the file that is to be sent 

byte[] array = new byte[(int) filepath.length()]; 

FileInputStream fileInputStream = new FileInputStream(filepath); 
BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream); 
//use bufferedInputStream to read to end of file 
bufferedInputStream.read(array, 0, array.length); 
//create objects for InputStream and OutputStream 
//and send the data in array to the server via socket 
OutputStream outputStream = socket.getOutputStream(); 
outputStream.write(array, 0, array.length); 

代號爲Windows窗體應用程序(接收文件)

TcpClient tcpClient = (TcpClient)client; 
NetworkStream clientStream = tcpClient.GetStream(); 

byte[] message = new byte[65535]; 
int bytesRead; 

clientStream.Read(message, 0, message.Length); 
System.IO.FileStream fs = System.IO.File.Create(path + dt); 
//message has been received 
ASCIIEncoding encoder = new ASCIIEncoding(); 
System.Diagnostics.Debug.WriteLine(encoder.GetString(message, 0, bytesRead)); 
fs.Write(message, 0, bytesRead); 
fs.Close(); 
+1

bytesRead將爲0,當你使用它。這不能成爲你的問題的原因,但表明你錯過了你的代碼的重要部分。 – dognose

+0

將整個文件加載到內存中並不是一個好主意。擁有固定的緩衝區大小也不是一個好主意。 –

+0

@AlexeiLevenkov他使用二進制輸入來使用ASCII輸出一個字符串。 –

回答

0

而不是閱讀完整的陣列到存儲和發送它後來到輸出流,你可以在同一時間讀/寫,只需使用「小」緩衝區字節數組。事情是這樣的:

public boolean copyStream(InputStream inputStream, OutputStream outputStream){ 
    BufferedInputStream bis = new BufferedInputStream(inputStream); 
    BufferedOutputStream bos = new BufferedOutputStream(outputStream); 

    byte[] buffer = new byte[4*1024]; //Whatever buffersize you want to use. 

    try { 
     int read; 
     while ((read = bis.read(buffer)) != -1){ 
      bos.write(buffer, 0, read); 
     } 
     bos.flush(); 
     bis.close(); 
     bos.close(); 
    } catch (IOException e) { 
     //Log, retry, cancel, whatever 
     return false; 
    } 
    return true; 
} 

在接收端,你應該這樣做:寫字節的一部分,你接受他們,而不是他們完全地存儲在內存中befor使用。

這可能無法解決您的問題,但無論如何都應該改進。