Use the URLConnection class. To read a server file,
try
{
URL url = new URL("http://www.myserver.com/test.html");
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
// if the file does not exist, the following will throw an exception:
InputStream is = urlConnection.getInputStream();
int r = is.read(buf);
}
catch (Exception ex)
{
System.out.println("Oh no!!!");
System.exit(1);
}
System.out.println("contents of text.html=" + new String(buf, 0));
Note that this will allow you to actually read the file, regardless of its contents.
I.e. the content handler is not called.
// This code will show the current directory of a java application.
// Enter a new directory in the text filed
// The press the ChangeDirectory button to change to the new directory
// Use the ListDirectory button to show a listing of files in the
// current directory.
//
import java.util.*;
import java.awt.*;
import java.io.*;
import java.applet.*;
public class setProps extends Applet
{
Label l1 = null;
TextArea ta1 = null;
TextArea ta2 = null;
TextField tf1 = new TextField(30);
Properties p = null;
public setProps() {
setLayout(new BorderLayout());
Panel p1 = new Panel();
p1.setLayout(new FlowLayout());
add("North", p1);
p1.add(new Button("ChangeDirectory"));
p1.add(new Button("ListDirectory"));
p1.add(tf1);
ta1 = new TextArea(10, 40);
ta2 = new TextArea(20, 40);
p1.add(ta1);
Panel p2 = new Panel();
p2.setLayout(new FlowLayout());
add("South", p2);
p2.add(ta2);
p = System.getProperties();
ta1.setText("Current directory: " + p.getProperty("user.dir"));
}
public boolean action(Event e, Object o) {
if ("ChangeDirectory".equals(o)) {
ta1.appendText("\n" + "Current directory before: " + p.getProperty("user.dir"));
//
// This is the code that changes the current directory to a new directory
// The system properties is a hashtable and the values in the table can be
// get/set using the get() and put() methods of the hashtable class. You can also
// get all the system properties using system.getProperties()
//
p.put("user.dir", tf1.getText());
System.setProperties(p);
ta1.appendText("\n" + "Current directory after: " + p.getProperty("user.dir"));
}
if ("ListDirectory".equals(o)) {
File f1 = new File(p.getProperty("user.dir"));
String fileList[] = f1.list();
int i, j = fileList.length;
ta2.setText("");
for (i = 0;i < j;i++)
ta2.appendText("\n" + fileList[i]);
}
return true;
}
public static void main(String args[]) {
Frame f1 = new Frame("Standalone Application");
setProps s1 = new setProps();
s1.init();
s1.start();
f1.add("North", s1);
f1.resize(400, 600);
f1.show();
}
}