//SAXNodes.java //Gerard Uffelman //XMLJ Homework #2 Answer Key Example import org.xml.sax.*; import org.xml.sax.helpers.DefaultHandler; import org.apache.xerces.parsers.SAXParser; import java.io.FileOutputStream; //output file stream import java.io.PrintStream; //FileOutputStream wrapper import java.io.IOException; //catch user io errors public class SAXNodes { public static void main(String[] args) { FileOutputStream fos; PrintStream ps; int nodeSize = 0; //Check input parameters if(args.length <= 2 || args.length > 3) { System.err.println("Invalid Command: Wrong number of arguments!"); System.err.println("Usage:\tjava SaxNodes graphFile nodeSize outputFile"); System.exit(0); } //Get maximum page size from input try{ Integer intWrapper = new Integer( args[1] ); nodeSize = intWrapper.intValue(); } catch(NumberFormatException nfe) { System.err.println("Error, invalid number: " + args[1]); return; } //Try to open file for output try{ fos = new FileOutputStream( args[2] ); } catch(IOException ioe) { System.err.println("Can't open output file: " + args[2]); return; } //Instantiate ps with fos ps = new PrintStream(fos); //Create NodeHandler class to handle SAX events and parse //input file. try{ NodeHandler handler = new NodeHandler(ps, nodeSize); SAXParser parser = new SAXParser(); parser.setContentHandler(handler); parser.setErrorHandler(handler); parser.parse(args[0]); } catch(Exception e){ e.printStackTrace(System.err); } ps.close(); //Close PrintStream } } //This class extends DefaultHandler and handles SAX events for us. //NodeHandler overloads startElement, startDocument, and endDocument from //DefaultHandler class NodeHandler extends DefaultHandler { PrintStream ps; int nodeSize; //Constructor takes reference to a printStram and nodeSize value public NodeHandler(PrintStream ps_in, int nodeSize_in) { nodeSize = nodeSize_in; if(ps_in != null) ps = ps_in; else System.err.println("Output PrintStream is null"); } //Write the following to our output file when the startDocument event occurs. public void startDocument() { ps.println(""); ps.println("
"); ps.println("