0

当我从磁盘读取文件时,我可以从文件中整理 XML,但是当我通过网络下载它时,我得到了这个错误。

[org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Premature end of file.]
    at javax.xml.bind.helpers.AbstractUnmarshallerImpl.createUnmarshalException

我假设网络输入流包含附加信息或什么?

作品

InputStream inputStream = null;
try {
    inputStream = new FileInputStream(filePath);
} catch (FileNotFoundException e) {
    e.printStackTrace();
}  

不工作

InputStream inputStream = null;

    try {
        inputStream = new URL(url).openStream();
    } catch (MalformedURLException e) {
        e.printStackTrace();

        } catch (IOException e) {
            e.printStackTrace();
        }

BulkDataRecordType bulkDataRecordType = getObjectFromXml(inputStream);

在另一个班级

public BulkDataRecordType getObjectFromXml(InputStream inputStream)
        {

            try {

                    JAXBContext jc = JAXBContext.newInstance(BulkDataRecordType.class);
                    Unmarshaller unmarshaller = jc.createUnmarshaller();
                    bulkDataRecordType = (BulkDataRecordType) unmarshaller.unmarshal(inputStream);

                } catch (JAXBException e1) {
                    e1.printStackTrace();
                }
4

1 回答 1

0

我首先检查字符串的校验和。一旦我对此发表评论,它就起作用了。我找到了一个创建两个新流的解决方案并且它有效。如果您有更好的解决方案,请告诉我。

public byte[] getCheckSumFromFile(InputStream inputStream)
    {
        MessageDigest md = null;

        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }

        InputStream is = null;

        try {
          is = new DigestInputStream(inputStream, md);
        }
        finally {
              try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }

        return md.digest();
    }

从原始创建两个流

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        try {

            byte[] buffer = new byte[1024];
            int len;

            while ((len = inputStream.read(buffer)) > -1 ) {
                byteArrayOutputStream.write(buffer, 0, len);
            }
            byteArrayOutputStream.flush();
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());

        // Get check sum of downloaded file
        byte[] fileCheckSum = getCheckSumFromFile(new ByteArrayInputStream(byteArrayOutputStream.toByteArray()));
于 2013-04-04T17:05:08.217 回答