简体   繁体   中英

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. My code is:


Sending the file from the desktop server to the Android client:

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:

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

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. 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.

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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