rtheunissen
rtheunissen

Reputation: 7435

Downloading files using Java randomly freezes

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();
    }
}

Upvotes: 5

Views: 1121

Answers (2)

Robert
Robert

Reputation: 1

O.K I think it's a laggy system or what by the guy who answered above me (Robert I think) but using ipv6 is going to be hard if you already no about ipv4 a lot.

Just a coincedence I'm named Robert :)

Upvotes: 0

Robert
Robert

Reputation: 42754

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”

Upvotes: 6

Related Questions