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();
bytesRead將爲0,當你使用它。這不能成爲你的問題的原因,但表明你錯過了你的代碼的重要部分。 – dognose
將整個文件加載到內存中並不是一個好主意。擁有固定的緩衝區大小也不是一個好主意。 –
@AlexeiLevenkov他使用二進制輸入來使用ASCII輸出一個字符串。 –