I am trying to download a zip file from a server using the following code but it gives me a tmp.zip of size 1kB. What is the mistake in this program?

try {
            URL url = new URL("http://www.nseindia.com/content/historical/DERIVATIVES/2013/JUN/fo18JUN2013bhav.csv.zip");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            InputStream in = connection.getInputStream();
            FileOutputStream out = new FileOutputStream("C://Temp/tmp.zip");
            copy(in, out, 1024);
            out.close();
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }     

        }   


    public static void copy(InputStream input, OutputStream output, int bufferSize) throws IOException {
        byte[] buf = new byte[bufferSize];
        int n = input.read(buf);
        while (n >= 0) {
          output.write(buf, 0, n);
          n = input.read(buf);
        }output.flush();
    }

Recommended Answers

All 7 Replies

Have you checked the file contents - eg is it an HTTP header or some such?

OK, Ignore previous post. There's nothing wrong with your code AFAICT.
I ran your code with zero changes (copy/paste into a shell class is all), got a 294k zip file which when unzipped gave me a Excel file which when opened in Excel displayed a load of data I didn't understand, but in an obviously reasonable format.
Over to you...

Does it refer to some technical keyword or just crude usage of English? Stupid question but still... :P

It's just a java file I have that has a few imports, a main method that calls a constructor... so I can drop in a piece of code like yours and execute it with minimum effort.

Got the problem... i needed a proxy to set proxy in my system and then use authenticator for the proxy... Thanks James for the feedback on correctness of the program...

OK, excellent! Please marked this "solved" for our knowledge base.
Thanks
J

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.