Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Downloading a file

 
Jithesh Kozhipurath
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Peter Storch
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 135
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Murthy: a small alteration is needed I guess...
 
Idly Vada
Ranch Hand
Posts: 135
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic