Why is the program throwing an IO Exception?
Hallo,
I am trying to figure out how the URL and Socket class works, to write a small program, which is downloading stuff, from a given internet side.
import TerminalIO.*;
import java.net.*;
import java.io.*;
publicclass Downloader
{
private String dlto;
private String dlfrom;
privateint dlport=80;
publicboolean done=false;
publicstaticvoid main(String [] args)
{
KeyboardReader in =new KeyboardReader();
char again='n';
do
{
System.out.println("Press enter if u want to save in the default folder");
String to = in.readLine("Where do u want to save?: ");
String from = in.readLine("From where do u want to download?: ");
Downloader dl =new Downloader(to, from);
System.out.println("It is "+dl.done+" that it is done");
again=in.readChar("Enter Y for yes if u want to run the program again,\nN if u don't:\n");
}while(again =='Y' || again =='y');
}
public Downloader(String where, String what)
{
dlto=where;
dlfrom=what;
start();
}
privatevoid start()
{
try
{
int len=0;
InetAddress addr = InetAddress.getByName(dlfrom);
//Displays from where the client is downloading
System.out.println("Downloading from: "+addr.getHostName());
System.out.println("At IP: "+addr.getHostAddress());
//tries to connect to witht the URL object, if it fails uses the Socket object
Socket sock=null;
URL url=null;
try
{
url =new URL(addr.getHostName());
}
catch(IOException e)
{
sock =new Socket(addr.getHostName(), dlport);
}
//getting the InputStream
InputStream in;
if(url ==null)
{
in=sock.getInputStream();
}
else
{
in = url.openStream();
}
//Saving the Downloaded Data
FileOutputStream out =new FileOutputStream(dlto);
System.out.println("Byte length, to download: "+in.available());
byte[] b =newbyte[in.available()];
System.out.println("Downloading to: "+dlto);
while (in.read(b) != -1)
{
out.write(b, 0, in.read(b));
}
//closing the output
out.close();
in.close();
done=true;
}
catch (MalformedURLException e)
{
System.out.println("Address not found");
}
catch (IOException e)
{
System.err.println(e.toString());
System.out.println("-->IO Exception");
}
}
}
this is the Code i just wrote, but like i said in the subject, it is throwing an IOException in anycase. I could even try to download data from my own harddrive. So what shall i do? The thing which is confusing me the most, is that it actually displays the Name and the IP address, so that it seems to have access to the internet, but somehow it does not download the things, but i have no clue why. Please help.
null

