// A Java
program that demonstrates a procedure that can be
// used to
download the contents of a specified URL.
import java.io.*;
import java.net.*;
public class DnldURL {
public static void main (String[ ] args) {
URL u;
InputStream is = null;
DataInputStream dis;
String s;
try {
u = new URL("http://200.210.220.1:8080/index.html");
is = u.openStream();
dis = new DataInputStream(new BufferedInputStream(is));
while ((s = dis.readLine()) != null) {
System.out.println(s);
}
} catch (MalformedURLException mue) {
System.out.println("Ouch - a MalformedURLException happened.");
mue.printStackTrace();
System.exit(1);
} catch (IOException ioe) {
System.out.println("Oops- an IOException happened.");
ioe.printStackTrace();
System.exit(1);
} finally {
try {
is.close();
} catch (IOException ioe) { }
}
}
}
Namesto fiksnega URL naslova bi lahko
le tega podali kot argument v ukazni vrstici. VV tem primeru bi morali
v programu uporabiti stavek te oblike:
Program je malo zakompliciran, ker
predvideva reakcije tudi v primerih, da se malo zatipkamo. Do izjeme MalformedURLException
bi na primer prišlo, če bi vtipkali namesto "http" pomotoma
"htp". Do izjeme IOException bi na primer prišlo, če
bi vpisali napačno ime datoteke.
Kako program prevedemo in preskusimo:
Ob predpostavki, da imamo pravilno inštaliran JDK, napišimo: