Java下载文件及常见错误

发布于 2024-11-15 04:44:27 字数 567 浏览 2 评论 0原文

我写了一个简单的下载器作为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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

朕就是辣么酷 2024-11-22 04:44:27

所以您想恢复下载。

如果从 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文