Description:
The piece of code below allows to download any file(i.e. binary file) from the internet. As you see, we're handling the exceptions properly. To download any file your desire,just replace the link in the program with a link of your choice
Solution:
package com.javaproblems.binaryfiledownload; import java.io.BufferedInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; public class PictureDownload { public static void main(String[] args) { URL url = null; InputStream is = null; BufferedInputStream bis = null; FileOutputStream fos = null; byte[] buff = null; int nb; try { //Choose your URL here url = new URL("http://4.bp.blogspot.com/-FiN1eeHw4pk" + "/UmE_3_7l00I/AAAAAAAAA_g/HRP2hP1XfTU/s1600/Untitled.png"); is = url.openStream(); bis = new BufferedInputStream(is); //1024 bytes = 1 MB //Our binary file is less than 1MB //Choose a size larger than your file buff = new byte[1024]; //Choose the same extension of the file //you're downloading fos = new FileOutputStream(new File("TrgtPhoto.png")); while((nb = bis.read(buff))>0) { fos.write(buff, 0, nb); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { //To not get a NullPointerException //in case our objects are null if(bis!=null) try { bis.close(); } catch (IOException e) { e.printStackTrace(); } //To not get a NullPointerException //in case our objects are null if(fos != null) try { fos.close(); } catch (IOException e) { e.printStackTrace(); e.printStackTrace(); } } } }
No comments :
Post a Comment