当我尝试下载文件时(在这种情况下它只是一个图像,但真正的应用程序是一个更新机制),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();
}
}