Reputation: 574
yI use the following code to download a file from internet.
//suppose I call this method inside main(String[] st) method.
private void download(String link){
URL url = new URL(link);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Accept-Encoding", "identity");
connection.setRequestProperty("connection", "close");
connection.connect();
save(connection.getInputStream());
}
private final int DOWNLOAD_BUFFER_SIZE = 10 * 1024;
private void save(InputStream inputStream) {
FileOutputStream fos;
try {
byte[] buffer = new byte[DOWNLOAD_BUFFER_SIZE];
int len;
fos = new FileOutputStream("FILE_PATH");
while ((len = inputStream.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//close streams, flush, etc.
}
}
Everything is OK and the code works fine. But when I change the value of DOWNLOAD_BUFFER_SIZE
to small numbers like 5
, an strange thing happens! When I change the value of DOWNLOAD_BUFFER_SIZE
to small numbers, and I turn off my internet connection, download continues for a while and does not stop! But when the value of DOWNLOAD_BUFFER_SIZE
is big like 10 * 1024
, everything is OK and when I turn off my connection download stops.
Can anyone help me? I want my download to be stopped when the value of DOWNLOAD_BUFFER_SIZE
is small and I turn off my internet connection.
I have seen this link but didn't help.
the EJP's answer does not contain the solution to solve this problem. i want DOWNLOAD_BUFFER_SIZE to be small, because of some reasons.
Please help me. I need your help. please:X
I apologize in advance if the grammar of my sentence is not correct. because I can't speak English well.
Upvotes: 0
Views: 86
Reputation: 310913
Because of the socket receive buffer. There is only so much in it. If you read small chunks out of it, it takes more reads.
I don't know why you want the size of your download buffer to be small. I usually use 4096 or 8192 bytes. Setting it to such a large value as 1MB is pointless unless the socket receive buffer in the kernel is equally large.
If you're concerned about network outages, as you should be, you should set a read timeout on the socket.
Upvotes: 2