如何打开/传递文件到XMLEventReader

时间:2014-07-09 18:27:02

标签: java xml file-io xml-parsing

我正在尝试创建一个程序,该程序将读取基于XML的文件,并且基本上会以更人性化的方式重写它,但我一直在运行XMLStreamException

这是我现在拥有的

`import java.io.File;

/* main purpose of this class is to read and write an XML document
   using tenants of STaX parsing. Eventually this should turn into a 
  class that will trim all but the outer 20% of the page
  */
 public class XMLReader {

public static void main(String args[]) {

    XMLInputFactory factory = XMLInputFactory.newInstance();
    System.out.println("FACTORY:" + factory);

    /*
     //TODO: make input and output file take args from command line
     using the programs mike sent as a reference.

     File file =null;
     if(args.length > 0) {
     file = new File(args[0]);
     }
     */
    InputStream in = null; //initializing the file we will read
    XMLEventReader reader = null; //intializing the eventreader
    try {
        in = new FileInputStream("/home/bzifkin/Proteus2/homer/src/main/java/ciir/proteus/parse/1105979_djvu.xml");
    } catch (FileNotFoundException e) {
        System.out.println("Could not find the file. Try again.");
    }

    try {
        reader = factory.createXMLEventReader(in);
     } 
        catch (XMLStreamException e) {
        System.out.println("There was an XML Stream Exception, whatever that means");
    }
}

}

这是我在XMLStreamException

上的堆栈跟踪

消息:com.sun.xml.internal.stream.XMLEventReaderImpl.nextTag(XMLEventReaderImpl.java:235)中的预期开始或结束标记     在ciir.proteus.parse.XMLReader.main(XMLReader.java:61)

1 个答案:

答案 0 :(得分:0)

如果我理解正确的注释,首先会得到一个FileNotFoundException,然后是XMLStreamException。

这听起来很合理,因为如果打开文件失败,您的代码会打印错误消息,但会继续处理“in”中的undefined(null)InputStream。

做这样的事情:

try {
    in = new FileInputStream("/home/bzifkin/Proteus2/homer/src/main/java/ciir/proteus/parse/1105979_djvu.xml");
    try {
        reader = factory.createXMLEventReader(in);
    } 
    catch (XMLStreamException e) {
        System.out.println("There was an XML Stream Exception, whatever that means");
    }
} catch (FileNotFoundException e) {
    System.out.println("Could not find the file. Try again.");
}