aspose file tools*
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
Author

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
import java.net.*;
import java.io.*;
class DownloadFile{
public static void main(String args[]){

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

int ch;

try{
url=new URL("http://www.idzeal.net"); //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
while((ch=bin.read())!=-1){
fout.write(ch);
}

//close the streams
fout.close();
bin.close();

}catch(Exception ex){
ex.printStackTrace();
}
}
}

Hope this helps you
----------
MurthyDN
Anonymous
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: http://aspose.com/file-tools
 
subject: Downloading a file