How To Download a File in Java

admin  

Here is a snippet that shows how to download a file in java. The snippet is tested and works just fine:

static public void download(String address, String localFileName) 
                                            throws MalformedURLException
                                                 , FileNotFoundException
                                                 , IOException
    {
        

        URL url = new URL(address);
        
        OutputStream out = new BufferedOutputStream(
                                new FileOutputStream(localFileName));
        URLConnection conn = url.openConnection();
        InputStream in = conn.getInputStream();

        byte[] buffer = new byte[1024];
        int numRead;
        int progress = 0;
        while ((numRead = in.read(buffer)) != -1) {
            out.write(buffer, 0, numRead);
            progress += 1024;
            System.out.print("\r" + (int)(progress / 1000)+ "kb");
        }            

        in.close();
        out.close();
    }