【发布时间】: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