I have an app that downloads a java file using the code below, problem is that it works fine for me and many others but some users get a “Connection timed out: connect” error, not really sure what could be causing this.
One guess is that it might be caused by the the buffer size which is set to 64kb. I have tried a smaller buffer size, like 4kb but found it took a lot longer to download, using the bigger buffer size was much faster, could it be that i need to use a smaller buffer and sacrifice speed?
Not really sure what is the correct way to do this, any help or solution on the best way to do this would be appreciated.
Thanks
public void downloadFile(URL url) throws Exception {
// reset percentage
percentage = 0;
// create buffer
byte buffer[] = new byte[65536];
// open connection
URLConnection urlconnection = url.openConnection();
// get file size
totalFileSize = urlconnection.getContentLength();
// get location to save file
String filename = getFileLocation(url);
InputStream inputstream = urlconnection.getInputStream();
FileOutputStream fos = new FileOutputStream(filename);
int bufferSize;
while ((bufferSize = inputstream.read(buffer, 0, buffer.length)) != -1) {
fos.write(buffer, 0, bufferSize);
currentFileSize += bufferSize;
percentage = (currentFileSize * 100) / totalFileSize;
}
}