Spartan Java

Download a file using Java

by on Oct.10, 2008, under Tips, Web related

Download a file using Java from a URL should be a simple task, well it is :P. If you just don’t want to think too much about it here is a sample method to do it.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public void download(String address, String localFileName) {
    OutputStream out = null;
    URLConnection conn = null;
    InputStream in = null;
    try {
        // Get the URL
        URL url = new URL(address);
        // Open an output stream to the destination file on our local filesystem
        out = new BufferedOutputStream(new FileOutputStream(localFileName));
        conn = url.openConnection();
        in = conn.getInputStream();
 
        // Get the data
        byte[] buffer = new byte[1024];
        int numRead;
        while ((numRead = in.read(buffer)) != -1) {
            out.write(buffer, 0, numRead);
        }            
        // Done! Just clean up and get out
    } catch (Exception exception) {
        exception.printStackTrace();
    } finally {
        try {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        } catch (IOException ioe) {
            // Shouldn't happen, maybe add some logging here if you are not 
            // fooling around ;)
        }
    }
}
:, , , , ,

4 Comments for this entry

Leave a Reply

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...