亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Java JAXB 解組器鏈接異常

Java JAXB 解組器鏈接異常

慕的地8271018 2021-08-19 22:35:54
背景:我正在嘗試使用 JAXB 解組器將 XML 解析為對象。我所做的:我使用 JAXB 本身來生成對象類并編寫了一些方法來解組 xml。public void xmlParser() {    try {        Acquirer acquirer = (Acquirer) readXml(Constants.XML_PATH);        System.out.println(acquirer.getDate());    } catch (JAXBException | IOException e) {        e.printStackTrace();    }}/** * Initializes of JAXB Context and Unmarshaller. */private static void createContext() {    try {        jaxbContext = JAXBContext.newInstance("com.test.xml.generated");        unmarshaller = jaxbContext.createUnmarshaller();    } catch (JAXBException e) {        e.printStackTrace();    }}/** * This reads the XML file from the resources in ClassPath. * * @param xmlFile XML file name as String with relative ClassPath * @return Unmarashalled XML file * @throws JAXBException * @throws IOException * @throws Exception */public Object readXml(String xmlFile) throws JAXBException, IOException {    if (jaxbContext == null) {        createContext();    }    InputStream stream = getClass().getClassLoader().getResourceAsStream(xmlFile);    BufferedInputStream buffredStream = new BufferedInputStream(stream);***Error:***    Object obj = unmarshaller.unmarshal(buffredStream);    buffredStream.close();    stream.close();    return obj; }錯誤在對象對象中.....例外:javax.xml.bind.UnmarshalException - with linked exception:[java.io.IOException: Stream closed]at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:246)at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:214)at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:157)at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:125)我設法搜索的內容:我使用 xml 驗證器來驗證 xml,它看起來很好。我還看到有人建議不要使用 InputStream 等。所以我嘗試使用 File file = new File(); 沒有什么。此外,我試圖檢查自動生成的對象類,但沒有發現任何可疑的東西。@XmlElement 和 Root 似乎定義得很好。PS我有這個xml的xsd方案(我使用這個xsd生成了所有對象類)。我什至使用在線工具來驗證它們,一切似乎都正確。Constants.XML_PATH = "/Acquirer.xml";
查看完整描述

1 回答

?
眼眸繁星

TA貢獻1873條經驗 獲得超9個贊

只需更改:

InputStream stream = getClass().getClassLoader().getResourceAsStream(xmlFile);

在:

InputStream stream = getClass().getResourceAsStream(xmlFile);

因為當你使用getClass().getClassLoader().getResourceAsStream(xmlFile)then 它返回null(沒有找到資源)BufferedInputStream然后將IOExceptionwhen 提供null而不是輸入流實例拋出到構造函數中。


查看完整回答
反對 回復 2021-08-19
  • 1 回答
  • 0 關注
  • 195 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號