More efficient way of getting text

import javax.xml.stream.*;
import java.net.*;
import java.io.*;

 
public class EfficientEventText {

  public static void main(String[] args) {
        
    if (args.length == 0) {
      System.err.println("Usage: java EfficientEventText url" );
      return;    
    }
        
    try {

      InputStream in;
      try {
        URL u = new URL(args[0]);
        in = u.openStream();
      }
      catch (MalformedURLException ex) {
          // Maybe it's a file name
          in = new FileInputStream(args[0]);
      }

      XMLInputFactory factory = XMLInputFactory.newInstance();
      XMLStreamReader parser = factory.createXMLStreamReader(in);
        
      Writer out = new OutputStreamWriter(System.out);
      for (int event = parser.next(); 
           event != XMLStreamConstants.END_DOCUMENT; 
           event = parser.next()) {
         if (event == XMLStreamConstants.CHARACTERS 
           || event == XMLStreamConstants.SPACE 
           || event == XMLStreamConstants.CDATA) {
             out.write(parser.getTextCharacters(), 
              parser.getTextStart(), parser.getTextLength());
         }
      }          
      out.flush();
      out.close();
    }
    catch (XMLStreamException ex) {
       System.out.println(ex);  
    }
    catch (IOException ex) {
      System.out.println("IOException while parsing " + args[0]);   
    }
        
  }

}

Previous | Next | Top | Cafe con Leche

Copyright 2007 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified March 18, 2004