File

2019-04-21 22:51 更新

File

这里我将结果输出到文件中,"D://test1.xml"不必手动创建,如果文件存在,将覆盖其中的内容。最后几行代码是用来测试数据是否成功输出到文件,与真正的编码没有必然联系。

    public void test2() throws JAXBException, SAXException {
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        File file = new File("D://test1.xml");// 将结果输出到文件
        marshaller.marshal(one, file);// 将自动创建test1.xml文件,并输出内容


        // 测试File中数据
        try (FileInputStream stream = new FileInputStream(new File("D://test1.xml"));){
            System.out.println(stream.read());// 测试File中数据的字节数
        } catch (Exception e) {
            // TODO: handle exception
        }
    }

也可以使用下面的方式,在项目的根目录下创建文件。刷新项目后,能在根目录下发现文件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");// 将结果输出到OutputStream
        marshaller.marshal(one, os);// 这是使用到 FileOutputStream
    }
以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号