Tuesday, December 13, 2011

Downloading files in Java via HTTP

Today a friend of mine asked me a small piece of code for an Android application that allows downloading a file via HTTP from a remote server and save it to a local file. I looked in my documents and quickly found a small download manager that did precisely that.
But now I will share with you a class in Java (android or not) that takes as argument a URL and the destination file and download it. Remember that this code is very basic and is only to give ideas.


public class DownloaderClass {
    public void downloadFile(URL url, File outputFile) {
        int BUFFER_SIZE = 4096;
       
        InputStream in = null;
        FileOutputStream fos = null;
       
        try {
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.connect();

            if (conn.getResponseCode() / 100 != 2) {
                throw new RuntimeException("Response Code: " + conn.getResponseCode());
            }
           
            in = conn.getInputStream();
            fos = new FileOutputStream(outputFile);

            byte data[] = new byte[BUFFER_SIZE];
            int numRead;
            while (((numRead = in.read(data)) != -1)) {
                fos.write(data, 0, numRead);
            }
        } catch (IOException e) {
            System.out.println(e);
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                }
            }

            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                }
            }
        }
    }
}



To use it, you just need 2 lines of code in your main.
DownloaderClass dc = new DownloaderClass();
dc.downloadFile(new URL("http://hackedprojects.blogspot.com/favicon.ico"),new File("c:\\favicon.ico"));



As you can see, it's simples :P

No comments:

Post a Comment