What happens if you call openStream twice? I have this code in which I open up a weather xml page and get information out of it. Unfortunately, the way I do it has me doing a linear search down the page for the line I need each time I want something - it should be pretty straightforward by looking at my code. However, I think the getElement method is downloading the page again and again each time I call it when all I realy want to do is download it, find what I need then be able to find the next thing I need and only redownload it when I explicitly want to. Can anyone just take a quick look at what I am doing wrong? This is my first program with any type of networking connection - and no, this isn't homework, just my own personal amusement.
-Thanks
import java.net.*;
import java.io.*;
import java.util.*;
class NOAAWeatherReader
{
private final String stationURLPrefix = "http://www.weather.gov/data/current_obs/";
private final String stationURLSuffix = ".xml";
private URL stationURL;
private InputStream is;
private BufferedReader weatherReader;
public NOAAWeatherReader(String stationID)
{
try
{
stationURL = new URL(stationURLPrefix + stationID + stationURLSuffix);
}
catch(MalformedURLException e)
{
System.out.println(e);
}
downloadPage();
}//constructor
private void init()
{
downloadPage();
weatherReader = new BufferedReader(new InputStreamReader(is));
}//init
private void downloadPage()
{
try
{
is = stationURL.openStream();
}
catch(IOException e)
{
System.out.println(e);
}
}//downloadPage
private String getLine(String xmlElement) throws ElementNotFoundException
{
init();
String elementLine = "";
boolean elementFound = false;
try
{
while((elementLine = weatherReader.readLine()) != null)
{
if(elementLine.indexOf(xmlElement) != -1)//elementLine contains xmlElement
{
elementFound = true;
break;
}
}
}
catch(IOException e)
{
System.out.println(e);
}
if(elementFound == false)
{
throw new ElementNotFoundException(xmlElement + " was not found in the document");
}
return elementLine;
}//getLine
public String getElement(String xmlElement)
{
String line = "";
try
{
line = getLine(xmlElement);
}
catch(ElementNotFoundException e)
{
System.err.println("The xml element: \"" + xmlElement + "\" was not found.");
}
int start = line.indexOf('>') + 1;
String returnString = line.substring(start,(line.length() - xmlElement.length()) - 3);
return returnString;
}//getElement
private void close()
{
try
{
weatherReader.close();
is.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
public static void main(String[] args)
{
NOAAWeatherReader nRead = new NOAAWeatherReader("KROC");
System.out.println(nRead.getElement("temp_f"));
System.out.println(nRead.getElement("wind_mph"));
nRead.close();
System.exit(0);
}
}//NOAAWeatherReader