如何使用Java下载文件的一部分? [英] How do I download part of a file using Java?
本文介绍了如何使用Java下载文件的一部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用此Java代码从Internet下载文件:
I'm using this Java code to download a file from the Internet:
String address = "http://melody.syr.edu/pzhang/publications/AMCIS99_vonDran_Zhang.pdf";
URL url = new URL(address);
System.out.println("Opening connection to " + address + "...");
URLConnection urlC = url.openConnection();
urlC.setRequestProperty("User-Agent", "");
urlC.connect();
InputStream is = urlC.getInputStream();
FileOutputStream fos = null;
fos = new FileOutputStream("myFileName");
int oneChar, count = 0;
while ((oneChar = is.read()) != -1) {
System.out.print((char)oneChar);
fos.write(oneChar);
count++;
}
is.close();
fos.close();
System.out.println(count + " byte(s) copied");
我想知道是否有办法只下载文件的一部分。
例如,要下载最后2MB的5MB文件。
I'd like to know if there is a way for me to download only a part of a file. For example, for a 5MB file to download the last 2MB.
推荐答案
如果服务器支持(和HTTP 1.1服务器应该),您可以使用范围请求:
If the server supports it (and HTTP 1.1 servers should), you can use range requests:
http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
同时,一次阅读一个字符是非常低效的 - 你应该读取块,比如4,16或32 KB。
Also, reading one character at a time is hugely inefficient - you should be reading in blocks, say 4, 16 or 32 KB.
这篇关于如何使用Java下载文件的一部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文