Skip to main content
Logo image

Java, Java, Java: Object-Oriented Problem Solving, 2024E

Section 15.4 From the Java Library: java.net.URL

Given a URL specification, how can we download its associated resource? Are there Java classes that can help us solve this problem? Fortunately, there are. First, the java.net.URL class contains methods to help retrieve the resource associated with a particular URL (Fig. 15.9). The URL class represents a Uniform Resource Locator. The URL() constructor shown here (there are others) takes a URL specification as a String and, assuming it specifies a valid URL, it creates a URL object.
Figure 15.4.1. URL class
If the URL specification is invalid, a MalformedURLException is thrown. A URL might be invalid if the protocol were left off or if it is not a known protocol. The following simple code creates a URL for the home page of our companion Web site:
URL url;
try {
 url =
  new URL("http://www.prenhall.com:80/morelli/index.html");
} catch (MalformedURLException e) {
 System.out.println("Malformed URL: " + e);
}
Note how we catch the MalformedURLException when we create a new URL.

Activity 15.4.1.

Try the program below to see the exception. Fix the URL.
Once we have a valid URL instance, it can be used to download the data or object associated with it. There are different ways to do this. The openConnection() method creates a URLConnection, which can then be used to download the resource. You would only use this method if your application required extensive control over the download process. A much simpler approach would use the openStream() method. This method will open an InputStream, which you can then use to read the associated URL data the same way you would read a file. This method is especially useful for writing Java applications. As you might guess, downloading Web resources is particularly easy from a Java applet. Now let’s search around for other methods that we can use.

Subsection 15.4.1 Image and Sound Resources

The java.applet.Applet class itself contains several useful methods for downloading and displaying Web resources. These methods are inherited by javax.swing.JApplet:
public class Applet extends Panel {
    public AppletContext getAppletContext();
    public AudioClip getAudioClip(URL url);
    public Image getImage(URL url);
    public void play(URL url);
    public void showStatus(String msg);
  }
As you see, both the getImage() and getAudioClip() methods use a URL to download a resource. An AudioClip is a sound file encoded in AU format, a special type of encoding for sound files. The getImage() method can return files in either GIF or JPEG format, two popular image file formats. The play() method downloads and plays an audio file in one easy step. For example, to download and play an audio clip within an applet requires just two lines of code:
URL url;
try {
  url = new
   URL("http://www.cs.trincoll.edu/~ram/jjj/slideshow/sound.au");
  play(url);
} catch (MalformedURLException e) {
    System.out.println("Malformed URL: " + url.toString());
  }
Similarly, to download (and store a reference to) an image is just as simple:
URL url;
try {
  url = new
   URL("http://www.cs.trincoll.edu/~ram/jjj/slideshow/slide0.gif") ;
  imgRef = getImage(url);
} catch (MalformedURLException e) {
    System.out.println( "Malformed URL: " + url.toString());
  }
So, if applets were still in fashion, then these would be the methods we need to implement our slide show. For an application, to load an image you need to declare the ImageRef and the call to read the image url is different:
URL url;
Image imageRef;
try {
  url = new
   URL("http://www.cs.trincoll.edu/~ram/jjj/slideshow/slide0.gif") ;
  imgRef = javax.imageio.ImageIO.read(url);
} catch (MalformedURLException e) {
    System.out.println( "Malformed URL: " + url.toString());
  }

Activity 15.4.2.

Try the program below. Try changing the URL to a broken one and see the exception.
For sound we need the javax.sound.sampled package. After constructing the URL, we need to set up an AudioInputStream, put the format of the stream into a DataLine.info object, and then get the line as a Clip, which we can then use to play the sound. The AudioSystem class is used heavily for this.
Clip clip; URL url = null;
try {
    url = new
    URL("http://cooplogic.com/cheyney/sound/liftMusic.wav");
    AudioInputStream audio =
  AudioSystem.getAudioInputStream(url); // get stream from url
    DataLine.Info info =
        new DataLine.Info(Clip.class, audio.getFormat()); // info needed for line
    if (!AudioSystem.isLineSupported(info)) {
  System.err.println("Audio file not supported: " + info);
  return;
    }
    try {
  clip = (Clip) AudioSystem.getLine(info); // the clip does the work
  clip.open(audio); // open the stream.
  clip.start(); // start the stream on a separate thread.
  // loop until clip has finished
  while (clip.getFramePosition() < clip.getFrameLength()) {
      try {
         Thread.sleep(10);
      } catch (Exception e) {
        e.printStackTrace();
      }
  }
    } catch (LineUnavailableException ex) {
         ex.printStackTrace();
    }  
  } catch (MalformedURLException e) {
    System.out.println("Malformed URL: " + url.toString()) ;
  } catch (UnsupportedAudioFileException ae) {
    System.out.println("not supported: " + ae) ;
  } catch (IOException ioex) {
    ioex.printStackTrace();
  }
We’ll use the URL() constructor to create a URL from a String, and we’ll use the javax.imageio.ImageIO.read(url) method to retrieve the images from the Web.
You have attempted of activities on this page.