Monday, July 25, 2016

How to create a file downloader in Java


Create a console based file downloader in Java


This tutorial is all about creating a java based downloader . So lets get started

This program uses a URLConnection to download the contents from the file.

import java.io.*; import java.net.*; import java.util.Scanner; public class filesfromsite { public static void main(String[] args) { Scanner inp = new Scanner(System.in); InputStream in = null; FileOutputStream fout = null; URLConnection connection = null; System.out.println("enter url"); String ur=inp.next(); System.out.println("name to save"); String kur = inp.next(); try{ URL url = new URL(ur); connection = url.openConnection(); in = connection.getInputStream(); fout = new FileOutputStream(kur); int b; while(((b = in.read()) != -1 )){ fout.write(b); } }catch(IOException exc){ System.out.println("connection error;"+ exc); }finally{ try{ if(in!= null) in.close(); if(fout != null) fout.close(); } catch(IOException exc){ System.out.println("Error closing stream "+ exc); } } } }

Lets see how the program works . The first is an InputStream called in , second one is URLConnection called connection , the third one is fileoutputStream called fout . Scanner asks for user input for url ,then the name of file and stores in ur and kur correspondly . After user input the url is defined and is tried to be opened by URLconnection .Then InputStream gets everything in in that connection.to get the output FileOutputStream is used . Then int b is defined then b stores everything passed by inputstream and saves it to FileOutputStream. and after that everything is closed and the program is successful in downloading.

Note :

the program will run until the file is downloaded completely and you have to define extension by yourself. The downloaded file will be on the same directory where your program is .


No comments:

Post a Comment