简体   繁体   English

通过Java套接字错误传输文件

[英]Wrong transfer of a file over Java socket

I am trying to transfer an XML file from a desktop server to an Android client but I get on the Android device just 1024 bytes of the entire file. 我正在尝试将XML文件从台式机服务器传输到Android客户端,但是在Android设备上却只有整个文件的1024个字节。 My code is: 我的代码是:


Sending the file from the desktop server to the Android client: 将文件从桌面服务器发送到Android客户端:

byte[] mybytearray = new byte[(int) filePianificazione.length()];

BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(filePianificazione));

bufferedInputStream.read(mybytearray, 0, mybytearray.length);

bufferedInputStream.close();

out.write(mybytearray, 0, mybytearray.length);

out.flush();

Receiving of the file from the Android client to the server: 从Android客户端到服务器的文件接收:

byte[] mybytearray = new byte[1024];

FileOutputStream fos = new FileOutputStream(file.getAbsolutePath());

BufferedOutputStream bos = new BufferedOutputStream(fos);

int bytesRead = in.read(mybytearray, 0, mybytearray.length);

bos.write(mybytearray, 0, bytesRead);

bos.close();

First you declare byte[] mybytearray = new byte[1024]; 首先,您声明byte[] mybytearray = new byte[1024];

Then you're doing a single 然后,您正在做一个

int bytesRead = in.read(mybytearray, 0, mybytearray.length);

bos.write(mybytearray, 0, bytesRead);

In your read code (Android client side), you're only reading 1024 bytes because that's the length of your input buffer, and you're only reading into it once. 在读取的代码(Android客户端)中,您仅读取1024字节,因为这是输入缓冲区的长度,并且只读取一次。 You need to have a while loop that'll continue to read from your input stream and then write that out until you reach EOF. 您需要有一个while循环,该循环将继续从输入流中读取,然后将其写出,直到达到EOF。

Something like: 就像是:

while(in.available() > 0)
{
    int bytesRead = in.read(mybytearray, 0, mybytearray.length);
    bos.write(mybytearray, 0, bytesRead);
}

The canonical way to copy streams in Java is as follows: 在Java中复制流的规范方法如下:

while ((count = in.read(buffer)) > 0)
{
  out.write(buffer, 0, count);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM