Java下载文件及常见错误
我写了一个简单的下载器作为Java applet。在一些测试中,我发现我下载文件的方式甚至不如 Firefox 的方式完美一半。
我的代码:
InputStream is = null;
FileOutputStream os = null;
os = new FileOutputStream(...);
URL u = new URL(...);
URLConnection uc = u.openConnection();
is = uc.getInputStream();
final byte[] buf = new byte[1024];
for(int count = is.read(buf);count != -1;count = is.read(buf)) {
os.write(buf, 0, count);
}
有时我的小程序工作正常,有时会发生意想不到的事情。例如,有时,在下载小程序的过程中会抛出 IO 异常,或者只是暂时失去连接,而无法返回到当前下载并完成它。
我知道对于单个没有经验的 Java 程序员来说,真正高级的方法太复杂了,但也许您知道一些技术来最小化出现这些问题的风险。
I wrote a simple downloader as Java applet. During some tests I discover that my way of downloading files is not even half as perfect as e.g. Firefox's way of doing it.
My code:
InputStream is = null;
FileOutputStream os = null;
os = new FileOutputStream(...);
URL u = new URL(...);
URLConnection uc = u.openConnection();
is = uc.getInputStream();
final byte[] buf = new byte[1024];
for(int count = is.read(buf);count != -1;count = is.read(buf)) {
os.write(buf, 0, count);
}
Sometimes my applet works fine, sometimes unexpected things happen. E.g. from time to time, in the middle of downloading applet throws an IO exception or just lose a connection for a while, without possibility to return to current download and finish it.
I know that really advanced way is too complicated for single unexperienced Java programmer, but maybe you know some techniques to minimalise risk of appearing these problems.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
所以您想恢复下载。
如果从 URL 读取时收到 IOException,则表明连接存在问题。
发生这种情况。现在您必须记下您已经下载了多少内容,并打开一个从那里开始的新连接。
为此,请在第二个上使用
setRequestProperty()
,并发送“我只需要以 ... 开头的资源范围”的正确标头字段。请参阅 HTTP 中的第 14.35.2 节范围检索请求 1.1 规范。不过,您应该检查响应中的标头字段,看看您是否真的返回了一个范围。So you want to resume your download.
If you get an IOException on reading from the URL, there was a problem with the connection.
This happens. Now you must note how much you already did download, and open a new connection which starts from there.
To do this, use
setRequestProperty()
on the second, and send the right header fields for "I want only the range of the resource starting with ...". See section 14.35.2 Range Retrieval Requests in the HTTP 1.1 specification. You should check the header fields on the response to see if you really got back a range, though.