How do I download part of a file using Java?

感情迁移 提交于 2019-12-04 05:53:39

问题


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");

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.


回答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

Also, reading one character at a time is hugely inefficient - you should be reading in blocks, say 4, 16 or 32 KB.




回答2:


Please have a look at Java: resume Download in URLConnection



来源:https://stackoverflow.com/questions/4127104/how-do-i-download-part-of-a-file-using-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!