Java: Download File

The following code will allow you to download a file in java from a source URL to a target File.

01public static void download(URL orig, File dest) throws IOException {
02    OutputStream os = null;
03    InputStream is = null;
04    try {
05        byte[] buf;
06        int count, length = 0;
07        os = new BufferedOutputStream(new FileOutputStream(dest));
08        is = orig.openConnection().getInputStream();
09        buf = new byte[4096];
10        while ((count = is.read(buf)) != -1) {
11            os.write(buf, 0, count);
12            length += count;
13        }
14    } finally {
15        is.close();
16        os.close();
17    }
18}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.