JavaRanch Home
 
Front Page FAQs Ranchers Categories Recent Changes To Do Upload

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 JavaDoc:java.lang.BufferedReader .

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.


Code


import java.applet.Applet;
import java.awt.FlowLayout;
import java.awt.Label;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;

public class HelloServerFile extends Applet 
{

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

        try
        {
            // 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
    
            reader.close();
        } // close try
        catch ( Exception e ) 
        {
            e.printStackTrace();
        } 
    } // close init
// close applet    


CodeBarnApplets
Front Page FAQs Ranchers Categories Recent Changes To Do Upload
Last Edited: 09 October 2007 What's Changed?
READ ONLY
 
Copyright © 1998-2008 Paul Wheaton | Home | Contact Us | Privacy | Register