 |
|
|
ShowRate.java
|
/*
* Author: Havard Rast Blok
* E-mail: 
* Web : www.rememberjava.com
*/
import java.io.*;
import java.net.*;
/**
* Reads a web page and extracts exchange rate information.
* It is designed for the "Aftenposten valutakurser" web page:
* http://www.aftenposten.no/nyheter/okonomi/
*
* However, it should be fairly easy to adjust to other's.
*
* IMPORTANT!
* Aftenposten is a registered tradmark, and this program
* is for educational purposes only.
*/
public class ShowRate
{
//final variables
private final String startRates = "<table width=100%>";
private final String startInfo = "sans-serif\">";
private final String endInfo ="</font";
private final String endRates = "</TABLE>";
private final int currencies = 20;
public ShowRate( URL theURL )
{
BufferedReader bufReader;
String line;
boolean foundRates;
int startInfoLength;
int infoIndex;
int endIndex;
String infoString;
boolean done;
int colCounter;
int rowCounter;
String rates[][];
//init variables
foundRates = false;
done = false;
startInfoLength = startInfo.length();
colCounter = 0;
rowCounter = 0;
rates = new String[currencies][4];
try
{
//open web page
bufReader = new BufferedReader( new InputStreamReader(theURL.openStream()) );
//read line by line
while( (line = bufReader.readLine()) != null && !done )
{
//System.out.println(line);
//check if the exchange rate table is found
if( !foundRates )
{
//if not, check if it starts in this line
foundRates = (line.indexOf(startRates) != -1);
}
//check if this line contains interesing information
else if( ( infoIndex = line.indexOf(startInfo)) != -1 )
{
//if it does, check if it is of the first four coloumns
//(The 5th is yesterday's news...)
if( colCounter < 4 )
{
//extract the information
//(no number conversion is done here
endIndex = line.indexOf(endInfo);
infoString = line.substring( infoIndex + startInfoLength, endIndex );
//put it in a 2d array
rates[rowCounter][colCounter] = infoString;
colCounter++;
}
else
{
//end of row (both on web page and in array)
rowCounter++;
colCounter = 0;
}
}
//check if exchange rate table is finished
else if( line.indexOf( endRates ) != -1 )
{
done = true;
}
}
//close the file when finished
bufReader.close();
}
catch( IOException e )
{
System.out.println( "ShowRate.ShowRate - error opening or reading URL: " + e );
}
//print data
for(int i = 0; i < currencies; i++)
{
for(int j = 0; j < 4; j++)
{
System.out.print("\t"+rates[i][j]);
}
System.out.println("");
}
}
public static void main( String args[] )
{
try
{
new ShowRate( new URL( "http://www.aftenposten.no/nyheter/okonomi/article.jhtml?articleID=34015&vistype=valutakurser" ) );
//Open web page
//new ShowRate(new URL(args[0]));
//Open file from disk instead
//File f = new File( args[0] );
//new ShowRate( f.toURL() );
}
catch (MalformedURLException e)
{
System.out.println("ShowRate.main - wrong url: " +e );
}
}// end main
}
|
|
|
 |