Search This Blog

How to download a file from internet Using java if URL is Given

Let us see how to download a file from internet in java. It is so simple. The following java program is a program which will download any file if the URL to the file to be downloaded is given. It also asks the user for destination to save the file. It displays the file size also. It also prints (displays) the progress of download. It uses the classes HttpURLConnection, URL, FileOutputStream, JFileChooser etc. The following java code is a simple java program to download a file from internet using URL. Here in this case, user has to give the file name and extension.




import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import javax.swing.JFileChooser; import javax.swing.JOptionPane; public class temp { public static void main(String[] args) { String address=JOptionPane.showInputDialog("Enter the url of the file to be downloaded."); //receiving URL of file as string if(address.equals("")||address==null) return;//exits if no url entered try { File savefile; long size,downloaded=0; URL url=new URL(address); JFileChooser jfc=new JFileChooser(); jfc.setDialogType(JFileChooser.SAVE_DIALOG); jfc.showSaveDialog(null);//asking for destination to save file if(jfc.getSelectedFile()==null) return;//exit if destination is not selected savefile=jfc.getSelectedFile();//getting target location selected by user HttpURLConnection ucn=(HttpURLConnection)url.openConnection();//open connection to the URL ucn.setRequestProperty("Range", "bytes="+0+"-");//setting request to get size of part of file to be downloaded //here download starts from beginning i,e from 0th byte ucn.connect(); size=ucn.getContentLengthLong();//get size of file InputStream is=ucn.getInputStream();//opening inputstream to read FileOutputStream fo=new FileOutputStream(savefile);//creating save file byte[] buf=new byte[1000000]; float perc,MBsize; int len; MBsize=(float)((float)size/1000/1000);//size in MB System.out.println("Filename: "+savefile.getPath()); System.out.println("File size: "+MBsize); while((len=is.read(buf))>0)//reading len number of bytes { downloaded+=len;//updating downloaded size fo.write(buf,0, len);//writing bytes to file perc=(float)downloaded*100/size;//calculation to display progress System.out.println(Float.toString(perc)+"% of "+Float.toString(MBsize)+" MB downloaded."); } is.close();//closing inputstream ucn.disconnect();//closing URLConnection fo.close();//closing file }catch(Exception ex){JOptionPane.showMessageDialog(null, ex);ex.printStackTrace();} } }

No comments:

Post a Comment