背景:我正在嘗試使用 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";
Java JAXB 解組器鏈接異常
慕的地8271018
2021-08-19 22:35:54