【问题标题】:Premature end of file. exception trying to parse xml from Zipinputstream文件过早结束。试图从 Zipinputstream 解析 xml 的异常
【发布时间】:2012-06-25 07:31:03
【问题描述】:

我正在尝试从 ZipInputStream 中提取 xml 文件和其他内容,并通过解析 zipinputstream 的 xml 创建我的对象。但是,当我没有 while 循环读取 inputStream 时,我得到了文件提前结束异常 - 对于以下代码或 Stream Closed。据我了解,ZipInputStream.getNextEntry 获取下一个条目输入流。

另外 - 当我通过创建一个实际的临时文件并传递输入流(如注释代码中所示)来运行它时 - 它处理得很好 - 但在我的情况下,我将无法写入磁盘 - 所以这一切都有发生在内存中。谁能告诉我我的代码哪里出错了,我能做些什么来解决它?

ZipEntry entry; 
Map<String, byte[]> otherElements = new HashMap<String, byte[]>();
        entry =((ZipInputStream)inputStream).getNextEntry();
        while (entry != null) {
            logger.debug("entry: " + entry.getName() + ", " + entry.getSize());
            System.out.println(entry.getName() + " - " + entry.getSize());

            if (entry.getName().equalsIgnoreCase("Document.xml")) {
                /*File file = new File("C:\\tmp.xml");
                FileOutputStream fos = new FileOutputStream();
                int read = 0;
                byte[] bytes = new byte[1024];

                while ((read = inputStream.read(bytes)) != -1) {
                    fos.write(bytes, 0, read);
                }
                InputStream fis = new FileInputStream();*/

                while(inputStream.available()>0){
                    inputStream.read();
                }

                myOutput = buildMyOutput((ZipInputStream)inputStream);
                //fos.close();
                //fis.close();

// method that takes the input and creates the java object
private MyObject buildMyOutput(InputStream xmlStream) throws Exception {

    // build my objects
    XStream xstream = ConvertUtil.getXStream();
    xstream.processAnnotations(MyObject.class);
    MyObject myOutput = (MyObject) xstream.fromXML(xmlStream);
    return myOutput;
}

【问题讨论】:

    标签: xml-serialization xml-parsing xstream zipoutputstream


    【解决方案1】:

    找出问题所在: XStream 正在丢失编码信息并将其设置为 null [codehaus 上的 JIRA 链接][1]https://jira.codehaus.org/browse/XSTR-441

    因此,基于此输入,我将输入流复制为 UTF-8,然后使用 UTF-8 编码格式调用 buildMyOutput 方法。 删除了以下 sn -p -

     while(inputStream.available()>0){
             inputStream.read();
     }
    

    并将 buildMyOutput 调用更改如下

    String xml = IOUtils.toString(zipInputStream, "UTF-8");
        InputStream documentXmlIS = IOUtils.toInputStream(xml);
        map = buildMyOutput(documentXmlIS);
    

    【讨论】:

    • 我后来意识到真正的罪魁祸首是我的 IDE 默认设置为使用 UTF-8 而不是系统默认设置。因此,根据您使用的 IDE,检查 IDE 的编码也是值得的(完全以非程序方式修复听起来程序化的问题!)
    猜你喜欢
    • 1970-01-01
    • 2017-04-20
    • 2012-04-28
    • 1970-01-01
    • 2013-04-08
    • 1970-01-01
    • 2011-12-20
    • 1970-01-01
    • 2012-06-22
    相关资源
    最近更新 更多