user3666515 user3666515 - 1 month ago 11x
Java Question

How do you use getDocumentBase() and getCodeBase() correctly in Java Applets?

I am working on a project, and I'm new to applets. I don't know how to find a file using these arguments. I know there is another question out there that is almost the same, but I want this in an easy, simplified way because I'm new to this. Any help would be awesome!!! Here is my code:

import java.applet.Applet;
import java.applet.AudioClip;
import java.awt.Graphics;

public class SoundDemo extends Applet
public void init()
AudioClip clip = getAudioClip( getCodeBase(), "sounds/Dragon Roost.wav" );;

public void paint( Graphics g )
g.drawString( "Now Playing Clip", 10, 10 );



It might help you to understand. Here I am reading a music file that is stored under music folder in src folder of my project as shown in below snapshot.

getDocumentBase() points to the bin folder (class-path) where all the classes are stored.

In your case it will fetch the music from bin/sounds/Dragon Roost.wav


Gets the URL of the document in which this applet is embedded. For example, suppose an applet is contained within the document:

The document base is:


Gets the base URL. This is the URL of the directory which contains this applet.

Sample code:


URL url = getDocumentBase();
AudioClip audioClip = getAudioClip(url, "music/JButton.wav");

Project structure:

enter image description here