File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Downloading a file Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Downloading a file " Watch "Downloading a file " New topic

Downloading a file

Jithesh Kozhipurath
Ranch Hand

Joined: Aug 27, 2003
Posts: 76
hai friends,
Can i download a file from a remote system( I mean a file from internet)to own machine using java program. The file should automatically saved into the filepath specifed in the program. It should not ask for the path, as in a normal download operation.

Jithesh K
Peter Storch
Ranch Hand

Joined: Jun 12, 2003
Posts: 74
What are you about to implement? A Java application, applet, ejb?
For applets you need special rights to write contents to the users machine.
For java applications you just can do anything you like. If the file is available via http just use the URLConnection class to refer to this file on the internet and get the input stream of this file. Then you can write the bytes to a local file of your choice.
For EJBs is file access restricted, but might work. Try it in your app server but your code might not be portable to other app servers.
[ September 04, 2003: Message edited by: Peter Storch ]
Idly Vada
Ranch Hand

Joined: Sep 02, 2003
Posts: 135
Folllwing code shows how to download a file and store in local file system.

//Program to download content from a webpage
//and store it in a local file
class DownloadFile{
public static void main(String args[]){

FileOutputStream fout;
BufferedInputStream bin;
InputStream in;
URL url;
URLConnection urlCon;
File file;

int ch;

url=new URL(""); //URL to be contacted
urlCon=url.openConnection();//Get URLConnection Object
in=urlCon.getInputStream(); //Get Inputstream
bin=new BufferedInputStream(in);//Wrap Inputstream with Buffered
//Input Stream

file=new File("idzeal.html"); //Name of the local file
fout=new FileOutputStream(file); //File output stream for the
//local file

// Read from the url and write
// to the local file

//close the streams

}catch(Exception ex){

Hope this helps you
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
Murthy: a small alteration is needed I guess...
Idly Vada
Ranch Hand

Joined: Sep 02, 2003
Posts: 135
Hi R�stem e Zal !
The code I've given is infact correct. In your code u've used readln() from a stream. One should remember that streams operate on bytes while readers operate on chars.
readline() should be used only with readers and not with streams.
I agree. Here's the link:
subject: Downloading a file
It's not a secret anymore!