使用Java下载文件随机冻结

rth*_*sen 5 java io

当我尝试下载文件时(在这种情况下它只是一个图像,但真正的应用程序是一种更新机制),InputStream似乎冻结了read.我很确定我的代码没问题,所以我想知道为什么会这样,如果它只是在我的电脑上.有人可以运行这个吗?请注意,Timer它仅用于调试目的.

非常感谢你.

这是一个显示问题的视频:视频

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

Rob*_*ert 5

您面临的问题是由Java 7引起的 - 详细说明要使IPv6具有比IPv4更高的优先级.

您可以通过设置系统属性将其更改为在Java 6中使用的IPv4 System.setProperty("java.net.preferIPv4Stack", "true");

此问题影响所有基于Java的软件,但仅在某些计算机上发生(可能取决于所使用的Internet连接):下载停止 - "TCP窗口已满"