Configuration File: named config.txt
title=My Favorite Playground
bkcolor=0000FF
textcolor=AAAA00
Java Code
import java.awt.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
public class ConfigFile extends JApplet
{
JPanel bkgrnd;
JLabel heading;
Color backcolor, textcolor;
String titletext;
String configFilename = "config.txt";
public void init( )
{
String config = readConfigFile( );
parseConfig( config );
bkgrnd = new JPanel( );
bkgrnd.setBackground( backcolor );
heading = new JLabel( titletext );
heading.setForeground( textcolor );
bkgrnd.add( heading );
setLayout( new BorderLayout( ) );
add( bkgrnd, BorderLayout.CENTER );
}
public void parseConfig( String cfg )
{
String[ ] lines, tokenkey;
lines = cfg.split( "\n" );
for( int i=0; i < lines.length; i++ )
{
tokenkey = lines[i].split( "=" );
// remove newline at end
String value = tokenkey[1].substring( 0, tokenkey[1].length( ) -1 );
if ( tokenkey[0].equals( "bkcolor" ) )
backcolor = new Color( Integer.parseInt( value, 16 ) );
else if ( tokenkey[0].equals( "textcolor" ) )
textcolor = new Color( Integer.parseInt( value, 16 ) );
else if ( tokenkey[0].equals( "title" ) )
titletext = value;
}
}
public String readConfigFile( )
{ String content;
try {
URL target = new URL( getCodeBase( ), configFilename );
URLConnection con = target.openConnection( );
con.connect( );
byte b[ ] = new byte[ 1024 ]; // byte array
int nbytes; // num bytes read in
String retVal = new String( );
BufferedInputStream in = new BufferedInputStream( con.getInputStream( ), 2048 );
while( (nbytes = in.read( b, 0, 1024 )) != -1 ) // while there's more to read
{ content = new String( b, 0, nbytes ); // get 1024 bytes of data
retVal += content;
}
in.close( ); // close connection
return retVal;
} catch ( Exception e ) { return "Error reading config file"; }
}
}
©2007-
by E.S.Boese. All Rights Reserved