-3

I have been trying to make this code work and also browsed stackoverflow for a while now but not able to find the answer. Hope you can help.

Trying to download a zip file from internet however it result in a zip file of 1 kb.

update: i have tried Long.MAX_VALUE, but the result is the same. I'm really not sure what is wrong. Normal text files works just file, but not zipfiles. PLease help.

private static void testDownload() {

    try {
        URL website = new URL("http://www.sec.gov/Archives/edgar/data/1027884/000102788418000013/0001027884-18-000013-xbrl.zip");
        ReadableByteChannel rbc = Channels.newChannel(website.openStream());
        FileOutputStream fos = new FileOutputStream("C:\\0001027884-18-000013-xbrl.zip");
        fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
    }catch(Exception e){
        System.out.println("EXCEPTION: " + e.getMessage());
        System.exit(2);
    }   
}
Ryan Chin
  • 11
  • 1
  • 1
    `1024` bytes to be precise, which is exactly what you tell the program to do. – luk2302 Jan 24 '18 at 18:21
  • 1
    What do you think `fos.getChannel().transferFrom(rbc, 0, 1024);` is doing? – Henry Jan 24 '18 at 18:24
  • Possible duplicate of [How to download and save a file from Internet using Java?](https://stackoverflow.com/questions/921262/how-to-download-and-save-a-file-from-internet-using-java) – Barney Jan 24 '18 at 18:36

2 Answers2

0

Using transferFrom() is potentially much more efficient than a simple loop that reads from the source channel and writes to this channel. Many operating systems can transfer bytes directly from the source channel into the filesystem cache without actually copying them.

Note: The third parameter in transferFrom is the maximum number of bytes to transfer. Integer.MAX_VALUE will transfer at most 2^31 bytes, Long.MAX_VALUE will allow at most 2^63 bytes (larger than any file in existence).

So , Here as you are specifying 1024 , i think thats why your zip file size is 1 KB . Please try specifying Long.MAX_VALUE .

Hope this solves your problem .

Sahil Aggarwal
  • 1,311
  • 1
  • 12
  • 29
  • Dear Sahil, Thanks. However i've tried Long.MAX_VALUE earlier but the result was the same. 1kb file zip file – Ryan Chin Jan 24 '18 at 18:46
  • Guys, i have tried several codes. Stil the same results. It always results in a zip file of 1 kb with the following file with the content : 301 Moved Permanently

    Moved Permanently

    The document has moved here.


    Apache Server at www.sec.gov Port 80
    – Ryan Chin Jan 26 '18 at 11:56
0

Okay guys, finally found the problem based on the output in the zipfiles.

Only had to convert HTTP to HTTPS which solved the problem

Ryan Chin
  • 11
  • 1