W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
這里我將結(jié)果輸出到文件中,"D://test1.xml"
不必手動(dòng)創(chuàng)建,如果文件存在,將覆蓋其中的內(nèi)容。最后幾行代碼是用來(lái)測(cè)試數(shù)據(jù)是否成功輸出到文件,與真正的編碼沒(méi)有必然聯(lián)系。
public void test2() throws JAXBException, SAXException {
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
File file = new File("D://test1.xml");// 將結(jié)果輸出到文件
marshaller.marshal(one, file);// 將自動(dòng)創(chuàng)建test1.xml文件,并輸出內(nèi)容
// 測(cè)試File中數(shù)據(jù)
try (FileInputStream stream = new FileInputStream(new File("D://test1.xml"));){
System.out.println(stream.read());// 測(cè)試File中數(shù)據(jù)的字節(jié)數(shù)
} catch (Exception e) {
// TODO: handle exception
}
}
也可以使用下面的方式,在項(xiàng)目的根目錄下創(chuàng)建文件。刷新項(xiàng)目后,能在根目錄下發(fā)現(xiàn)文件file.xml
。
public void test2_2() throws Exception {
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
FileOutputStream os = new FileOutputStream("file.xml");// 將結(jié)果輸出到OutputStream
marshaller.marshal(one, os);// 這是使用到 FileOutputStream
}
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: