Download a file using Java
by ricardoz 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 ;) } } } |
June 29th, 2009 on 1:04 pm
Good post, thanks for posting
July 8th, 2011 on 3:33 am
Thanks dude. Lemme try this
January 25th, 2012 on 4:12 am
I got output. but with 0 kb. Any suggestion?
January 25th, 2012 on 7:44 am
@Baskar: check that the user used by your java process has read permission over the file