【问题标题】:How to open/pass a file into XMLEventReader如何打开/传递文件到 XMLEventReader
【发布时间】:2014-07-09 18:27:02
【问题描述】:

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

这是我现在拥有的

`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)

【问题讨论】:

  • 你是什么意思它没有工作。您看到了什么异常或错误?
  • 一个FileNotFoundException,然后是一个XMLStreamException
  • 文件在哪里?使用/1105979_djvu,它应该位于文件系统的根目录。如果文件有扩展名,你需要指定它,否则 -> FileNotFoundException!
  • 我运行 pwd 并将我当前的路径粘贴到文件名上,这很有效!现在我需要做的就是弄清楚为什么我会收到XMLStreamException
  • 最终这就是导致异常的原因。我不知道 .djvu 但似乎不符合 xml。

标签: java xml file-io xml-parsing


【解决方案1】:

如果我对 cme​​ts 的理解正确,您首先会收到 FileNotFoundException,然后是 XMLStreamException。

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

改为这样做:

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.");
}

【讨论】:

    猜你喜欢
    • 2016-08-17
    • 2016-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-01
    相关资源
    最近更新 更多