0

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.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Sorin
  • 31
  • 2
  • 4

2 Answers2

5

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.

Lawrence Dol
  • 63,018
  • 25
  • 139
  • 189
3

Please have a look at Java: resume Download in URLConnection

Community
  • 1
  • 1
mezzie
  • 1,276
  • 8
  • 14