Java Programming   Java Programming
 |Sofia Home | Content Gallery |
Home
Syllabus
Schedule
Lessons
Assignments
Resources

Lesson 13.5 Network Streams

This section will teach you how to use Java's URL classes and its network streams to read files stored on remote computers just as if you were reading files located on your local machine.

Java's URL class, contained in the java.net package, provides the easiest way to open a network data connection. Reading from a URL is just about as easy as reading from a file.

Java's URLConnection class makes it easy to find out information about a particular URL. 

What is a URL?

As you remember from the first week of class, URL stands for Uniform Resource Locator. URLs are a scheme to identify any document located on the Internet, as well as to identify the program that should deliver that document.

Consider the URL:

ftp://myserver.com/home/apache/html/index.html

This URL identifies the file named index.html on the host machine named myserver.com. But that's not all. It also specifies:

  • the path to the file.
  • the protocol used to retrieve that file. 

The use of the ftp:// URL says, in essence, "Hand the file descriptor

/home/apache/html/index.html

over to the FTP server program, and let it find the file."

This URL:

http://myserver.com/index.html

identifies exactly the same file as the previous URL.

The http:// URL says "Hand the file descriptor

/index.html

over to the HTTP server program, [usually httpd], and let it find the file."

Notice that each individual server, [the FTP server or the HTTP server], has its own particular way of locating a file. The HTTP server uses what is called the document root, while the FTP server uses the root of the file system.

Back to Top

URL Objects

Before you can read from a remote file, you have to create a URL object. The URL class has several different constructors, but the ones you'll use most often are:

URL(String);
URL(URL, String);

The first constructor takes a complete String, just like you'd type into your Web browser's location window:

URL u = new URL("http://www.javasoft.com");

The second form is used when you need to create a relative URL. In such a case, the second String cannot be an absolute URL. Here's an example using the second constructor:

URL u2 = 
    new URL(getCodeBase(), "readme.txt");

Because it's possible for you to enter an incorrect URL, the URL constructor throws a MalformedURLException. This is a checked exception so it must be caught.

Using URL Objects

Once you've created a URL object, there are several things you can do with it. Probably the most immediately useful is to call its openStream() method so you can read the information that it contains.

Let's create an applet, call it ReadRemoteFiles.java, that lets us put in a URL, open the file it represents, and display the results in a TextArea.

Step 1: Basic Applet

First create a basic applet skeleton. In addition to the regular imports, you'll need the java.net package for the URL class and the java.io package for the InputStream class.

Add a TextArea and a TextField, and lay them out using BorderLayout. Your code should look like this:

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.io.*;
import java.net.*;

public class ReadRemoteFiles extends Applet
 implements ActionListener
{
  TextArea  ta = new TextArea();
  TextField tf = new TextField();

  public void init()
  {
    setLayout(new BorderLayout());
    add(tf, "North");
    add(ta, "Center");
    tf.requestFocus();
    tf.addActionListener(this);
  }
  // Add actionPerformed() method here
} 

Back to Top

Step 2: Open the URL

The next step is to retrieve the user's URL String from the TextField when the user presses ENTER, and convert it to a URL object. We'll do that in the actionPerformed() method.

Here are the steps:

  1. Create a URL variable and set it to null.
  2. Create an InputStream variable and set it to null.
  3. Write a try-catch block that catches Exception.
  4. Construct the URL inside the try block.
  5. Send your URL object an openStream() message and assign the resulting stream to your InputStream variable.
  6. In your catch block, use e.getMessage() to display any errors in the TextArea.

Here's what your code should look like:

public void actionPerformed(ActionEvent ae)
{
  URL u = null;
  InputStream in = null;

  try   {
    String urlStr = tf.getText();
    u = new URL(urlStr);
    in = u.openStream();

    // Read and process the data here
  }
  catch(Exception e) {
    ta.append("Problem\n");
    ta.append(e.getMessage() + "\n");
  }
  finally {
    try {
      if (in != null) in.close();
    } catch(IOException e1) { }
  }
}

Back to Top
Step 3: Read the Data
Reading the data from your InputStream is just like reading the data from a FileInputStream. It really doesn't make any difference that the data source is a network connection instead of a local file.

[Well, not much difference. You can't read using byte arrays from a network connection because the available() method always returns 0.]

Here's the plan to read from your URL's InputStream:

  1. Create a local String named outStr, and initialize it to the empty String, just as you did when reading byte-by-byte from a FileInputStream.
  2. Create a local int named ch which you'll use to read the characters from the stream.
  3. Write a loop that reads characters from your stream until it returns -1.
  4. Cast each int to a char, and concatenate it with your String outStr.
  5. When the loop is finished, use setText() to display your String in the TextArea.

Here's what your code should look like: 

String outStr = "";
int ch;

while ((ch = in.read()) != -1)
     outStr += (char)ch;

ta.setText(outStr);

Once you've finished this code, add a finally block below your catch block and close your InputStream. Then you're done.

Back to Top

Try It Out

Here's the ReadRemoteFiles applet running. Let's try a few things:
  1. Copy the URL of this page from your Web browser's location bar and paste it into the applet's TextField. What happens? Type in the HTTP address of your home page. What happens?
  2. Type in http://www.whitehouse.gov. What happens?

When you type in the URL for the current page, you should see the actual text that makes up this page. Your home page and the White House Web address, however, are not as successful. Here's why. Just as applets are forbidden to read files from you local machine, they are also restricted to retrieving files from the same host that served the applet. Basically, you can get any Web page from the machine hosting the CS170 Web pages, but you can't connect to any other server. This policy is not actually enforced by Java itself. Instead, each Web browser enforces its own security policy. If you download ReadRemoteFiles.java and run it in a Java 1.1 appletviewer, [such as that supplied with the built-in MS JVM], you won't have any problem connecting to any site on the 'Net, as you can see here:

Running the ReadRemoteFiles applet in appletviewer.
You may, or may not be able to connect via appletviewer. If you get a message like that shown below, just open the AppletViewer properties dialog from the Applet menu, and change the Network access to "Unrestricted" from "Applet Host".
Changing the appletviewer Network Access policies in JDK 1.1.
If you are using the Java 2 SDK, you'll notice that you don't have a Network Access drop-down. To get a Java 2 applet to work in this case you have to modify a policy file on your local machine, using a set of rules that are too Byzantine for me to understand, much less for this lesson. If you are using Java 2 and want to run this program, just make it an application instead of an applet.
Back to Top

Using URLConnection

In addition to retrieving the information from a URL, you might also like to know a little about the URL itself. The URLConnection class gives you that information.

Using the URLConnection class is a three-step process, once you've opened your URL:

  1. Create a URLConnection object by sending your URL object the openConnection() message. Send your URLConnection object the connect() message.
  2. Ask the URLConnection object for some info.

What kind of information can you get back? Here's a table:

Information
Java Code
Content Type getContentType();
Encoding getContentEncoding();
Length getContentLength();
Date new Date(getDate());
Last Modified new Date(c.geLastModified());
Expiration new Date(c.getExpiration());

The ReadRemoteInfo Applet

Here's a modification of the ReadRemoteFiles applet, called ReadRemoteInfo.java. You can download it and run it on your local machine, provided you are using Java 1.1, or try it out from here.

Remember, when run as an applet through your Web browser, your browser's security policies are in effect. If you run it through appletviewer, however, as shown here, you can connect to any site at all. [Again, assuming you are using Java 1.1.]

Running the ReadRemoteInfo applet in appletviewer.

Something to Talk About

Here's something to try! Download and run the ReadRemoteInfo applet on your local machine. What happens when you type in the URL
http://www.whitehouse.gov

Please continue to the next section of this lesson.

 

Back to Top

 

Content Developed by Stephen Gilbert, Licensed under a Creative Commons License
Published by the Sofia Open Content Initiative
© 2004 Foothill-De Anza Community College District &The William and Flora Hewlett Foundation