【发布时间】:2012-08-18 01:45:55
【问题描述】:
当我尝试下载文件时(在这种情况下它只是一个图像,但真正的应用程序是一个更新机制),InputStream 似乎冻结在read 上。我很确定我的代码没问题,所以我想知道为什么会发生这种情况,以及它是否只是在我的计算机上。有人可以运行这个吗?请注意,Timer 仅用于调试目的。
谢谢。
这是一个显示问题的视频: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();
}
}
【问题讨论】:
-
我连续运行了 10 次没有问题。
-
我刚刚在我的系统上尝试了代码,下载小丑完全没有问题:)。这是在带有 IcedTea 6 JRE 的 XUbuntu 12.4 上。我唯一想到的就是刷新循环中的输出流——但我看不出这会如何改变任何事情。
-
我会试试的。不过,我几乎每次尝试它都会冻结!
-
你运行的是什么操作系统和java?这可能是特定于平台的问题。或者它可能只是你的互联网连接......
-
这个问题听起来与我在 SuperUser 上提出的问题非常相似 - 它包含一个非常有趣的答案:superuser.com/questions/410883/downloads-stops-tcp-window-full