发送/接收.txt文件从Android到PC,而不是整个文件发送
本文关键字:文件 PC 接收 txt Android 发送 | 更新日期: 2023-09-27 18:13:41
我试图使一个Android应用程序,发送一个。txt文件到我的电脑上的Windows窗体应用程序。问题是,不是整个文件被发送(我还没有能够找出问题是否在发送或接收端)。我只从.txt文件中间的某个地方得到接收方的随机部分。我做错了什么?奇怪的是,它已经完美地工作了几次,但现在我从来没有得到文件的开始或结束。
Android应用程序是用Java编写的,Windows窗体应用程序是用c#编写的。Filepath是我的文件的名称。这里的问题是什么?
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();
您可以同时进行读/写操作,而不是将整个数组读入内存并随后将其发送到输出流,并且只使用一个"小"缓冲区字节数组。像这样:
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;
}
在接收端,你应该做同样的事情:当你接收到它们时,写入一部分字节,并且在使用之前不将它们完全存储到内存中。
这可能不能解决你的问题,但无论如何你都应该改进。