transferFrom returns 0 before end of channel is reached

Hey, I have this code for downloading a file via HTTP and it mostly works fine. However this crashes for a friend of mine with a very poor network connection (“mobile internet”, 2-10kb/s download speed) because transferFrom() returns 0 before the full file is downloaded (eg. downloaded 2327 / 3163 bytes). I know the filesize in advance, however I don’t want to loop until the received amount = expectedSize because if I modify the file while someone is downloading it they’ll get stuck in an infinite loop. Anyone know how I can fix this?

Thanks,
roland


try
{
	URL fileURL = new URL(urlOfFileToDownload);
	InputStream stream = fileURL.openStream();
	
	ReadableByteChannel rbc = Channels.newChannel(stream);
	if (!fileExists(saveLocation))
		createEmptyFile(saveLocation);
	FileOutputStream fos = FileManager.GetFileOutputStream(saveLocation);
	int totalNumBytesTransferred = 0;
	int bytesTransferred = 0;
	do
	{
		bytesTransferred = (int)fos.getChannel().transferFrom(rbc, totalNumBytesTransferred, TRANSFER_CHUNK_SIZE); //TRANSFER_CHUNK_SIZE=512*1024
		totalNumBytesTransferred += bytesTransferred;
	} while (bytesTransferred > 0);
	
	fos.close();
	
	//check file
	if (totalNumBytesTransferred != expectedFileSize) //I know expectedFileSize
		throw new UnsupportedOperationException("Failed to fully download file " + urlOfFileToDownload +": wrong filesize (expected " + expectedFileSize +", received "+totalNumBytesTransferred);
	
	success = true;
}
catch(Exception e)
{
	error = e.getMessage();
	e.printStackTrace();
}