Java file download accidentally freezes

When I try to upload a file (in this case it is just an image, but the real application is an update mechanism) InputStream, it seems to freeze on read. I am sure my code is ok, so I wonder why this is happening, and if it's just on my computer. Can someone please run this? Please note that this is Timerjust for debugging purposes.

Thank you.

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();
    }
}
+5
source share
2 answers

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

IPv4, Java 6, System.setProperty("java.net.preferIPv4Stack", "true");

Java, ( -): - " TCP"

+5

O.K , , (, ) ipv6 , ipv4.

:)

0

All Articles