【问题标题】:JAXB Java Marshalling errorJAXB Java 编组错误
【发布时间】:2014-11-18 19:07:26
【问题描述】:

我正在尝试使用 JAXB 编组一个简单的 Java 类,但我遇到了错误。我正在寻找有关修复以下错误的建议 这些是错误:

javax.xml.bind.JAXBException
 - with linked exception:
[java.io.FileNotFoundException: C:\file.xml (Access is denied)]
    at javax.xml.bind.helpers.AbstractMarshallerImpl.marshal(Unknown Source)
    at JAXBExample.main(JAXBExample.java:23)
Caused by: java.io.FileNotFoundException: C:\file.xml (Access is denied)
    at java.io.FileOutputStream.open(Native Method)
    at java.io.FileOutputStream.<init>(Unknown Source)
    at java.io.FileOutputStream.<init>(Unknown Source)
    ... 2 more

当我尝试运行 JAXB 编组的类时出现错误。它是从教程网站 (http://www.mkyong.com/java/jaxb-hello-world-example/) 下载的,所以它应该是正确的。

这是元帅类:

import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class JAXBExample {
    public static void main(String[] args) {

      Customer customer = new Customer();
      customer.setId(100);
      customer.setName("mkyong");
      customer.setAge(29);

      try {

        File file = new File("C:\\file.xml");
        JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

        // output pretty printed
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        jaxbMarshaller.marshal(customer, file);
        jaxbMarshaller.marshal(customer, System.out);

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

Marshaling 类引用了一个 Customer 类。 这是客户类:

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Customer {

    String name;
    int age;
    int id;

    public String getName() {
        return name;
    }

    @XmlElement
    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    @XmlElement
    public void setAge(int age) {
        this.age = age;
    }

    public int getId() {
        return id;
    }

    @XmlAttribute
    public void setId(int id) {
        this.id = id;
    }

}

【问题讨论】:

  • 您是否有权限读取该文件?还是 file.xml 在其他地方打开?

标签: java jaxb marshalling


【解决方案1】:

该错误似乎与 XML 无关 - 您根本无法访问您尝试打开的文件。

尝试删除“C:\\”,以便文件位于工作目录而不是 C 驱动器的顶部。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-16
    • 1970-01-01
    • 2018-12-31
    • 1970-01-01
    • 2011-09-01
    • 1970-01-01
    相关资源
    最近更新 更多