使用Java下载文件随机冻结 [英] Downloading files using Java randomly freezes

查看:95
本文介绍了使用Java下载文件随机冻结的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

谢谢你。

以下是显示问题的视频:视频

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


推荐答案

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

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

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

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");

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

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"

这篇关于使用Java下载文件随机冻结的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆