Applet:code=HelloServerFile.class:codebase=codebarn/:width=130:height=150:Applet
Explanation of HelloServerFile applet
Number of files: 2 (HelloS
erverFile.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:
- Create a URL object which represents the URL of the text file
- Get an InputStream on that URL
- Read from the Stream
HelloS
erverFile does a very simple readLine on a
JavaDoc:java.lang.BufferedReader .
To display the text from the text file, HelloS
erverFile 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()
{
setLayout( new FlowLayout( FlowLayout.CENTER, 1000, 5 ) );
String line = null;
try
{
URL textURL = new URL( getCodeBase() , "test.txt" );
BufferedReader reader = new BufferedReader( new InputStreamReader( textURL.openStream() ) );
while ( ( line = reader.readLine() ) != null )
{
add( new Label( line ) );
}
reader.close();
}
catch ( Exception e )
{
e.printStackTrace();
}
}
}
CodeBarnApplets