JavaRanch Home    
This page:         last edited 23 October 2013         What's Changed?         Edit

Code Barn Hello Server File   

You must turn on Java for applets to work.

Explanation of HelloServerFile applet

Number of files: 2 (HelloServerFile.class, and a text file named test.txt)

What it does: Gets the text from a text file on the server and displays each line from the text file on the screen. Applets can't actually *read* from the server, but the URL class allows an applet to GET text from a URL.

To GET text from a URL:

  1. Create a URL object which represents the URL of the text file
  2. Get an InputStream on that URL
  3. Read from the Stream

HelloServerFile does a very simple readLine on a .

To display the text from the text file, HelloServerFile creates a unique Label object to display each line of text. This is just for an example of a way to dynamically generate components based on information in a text file. At compile-time, there was no way to know how many Labels would be needed.


import java.applet.Applet;
import java.awt.FlowLayout;
import java.awt.Label;

public class HelloServerFile extends Applet 

    public void init() 
        // everything happens in init
        setLayout( new FlowLayoutFlowLayout.CENTER, 10005 ) );
        String line = null;

            // create a URL (the URL for the text file on the server) then open a stream
            URL textURL = new URL( getCodeBase() , "test.txt" ); 
            BufferedReader reader = new BufferedReadernew InputStreamReader( textURL.openStream() ) );
            // now read the lines one at a time 
            while ( ( line = reader.readLine() ) != null ) 
                add( new Label( line ) );
            } // close while loop
        } // close try
        catch ( Exception e ) 
    } // close init
// close applet    


JavaRanchContact us — Copyright © 1998-2014 Paul Wheaton