0

我正在尝试制作一个将 .txt 文件发送到我计算机上的 Windows 窗体应用程序的 Android 应用程序。问题是没有发送整个文件(我无法找出问题是在发送端还是接收端)。我只从 .txt 文件中间的某个地方到接收方得到一个随机部分。我究竟做错了什么?奇怪的是,它已经完美地工作了几次,但现在我从来没有得到文件的开头或结尾。

Android 应用程序是用 Java 编写的,Windows 窗体应用程序是用 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();
4

1 回答 1

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;
}

在接收端你应该做同样的事情:当你收到它们时写入一部分字节,并且在使用之前不要将它们完全存储到内存中。

这可能无法解决您的问题,但无论如何您都应该改进。

于 2013-05-15T07:10:26.023 回答