Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Downloading files using Java randomly freezes

Tags:

java

io

When I try to download a file (in this case it's just an image but the real application is an updating mechanism), the InputStream seems to freeze on read. I'm pretty sure my code is okay, so I'm wondering why this happens and if it's just on my computer. Could someone please run this? Please note that the Timer is simply for debugging purposes.

Thank you kindly.

Here is a video showing the problem: Video

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.URL;
import javax.swing.Timer;

public class FileDownloader {

    public final static int BUFFER_LENGTH = 1 << 14;

    private static Timer timeoutTimer = new Timer(5000, new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("Timeout");
            System.exit(0);
        }
    });

    public static void main(String [] args) throws Exception{
        URL url = new URL("http://host.trivialbeing.org/up/tdk-aug3-jokr-high-res-2.jpg");
        download(url, new File("joker.jpg"));
    }

    public static void download(final URL url, final File dest) throws IOException {
        FileOutputStream fos = new FileOutputStream(dest);
        BufferedOutputStream out = new BufferedOutputStream(fos);
        BufferedInputStream in = new BufferedInputStream(url.openStream());
        byte[] buf = new byte[BUFFER_LENGTH];
        int bytesRead;
        int bytesWritten = 0;
        timeoutTimer.start();
        while ((bytesRead = in.read(buf, 0, BUFFER_LENGTH)) != -1) {
            timeoutTimer.restart();
            out.write(buf, 0, bytesRead);
            out.flush();
            bytesWritten += bytesRead;
            System.out.println(bytesWritten / 1024 + " kb written");
        }
        in.close();
        out.close();

        System.out.println("Finished");
        fos.close();
    }
}
like image 209
rtheunissen Avatar asked Jul 25 '12 13:07

rtheunissen


1 Answers

The problem you are facing is caused by Java 7 - in detail that to gives IPv6 a higher priority than IPv4.

You can change it back to IPv4 as it was used in Java 6 by setting the system property System.setProperty("java.net.preferIPv4Stack", "true");

This problem affects all Java based software but only occurs on some computers (may depend on the internet connection used): Downloads stops - “TCP Window Full”

like image 91
Robert Avatar answered Oct 20 '22 05:10

Robert