我正在尝试创建一个将.txt文件发送到计算机上的Windows窗体应用程序的Android应用程序。问题是不是整个文件被发送(我无法确定问题是在发送方还是接收方)。我只从.txt文件中间的某个地方获得一个随机部分到接收方。我究竟做错了什么?奇怪的是,它已经完美地工作了几次,但现在我永远不会得到文件的开头或结尾。
Android应用程序是用Java编写的,Windows Forms应用程序是用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();
答案 0 :(得分: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;
}
在接收端你应该这样做:在收到它们时写下一部分字节,而不是将它们完整地存储到内存中。
这可能无法解决您的问题,但无论如何都应该改进。