在Java中创建新的JAXBContext实例时出现jaxb NullPointerException
我有一个类可以将我的对象输出为XML,反之亦然。我的方法是使用JAXB和try/catch
当我运行程序时,我得到错误:
New Drawing object could not me instaned.Exception in thread "main" java.lang.NullPointerException
at se.miun.vife1700.dt062g.jpaint.FileHandler.saveToXML(FileHandler.java:21)
at se.miun.vife1700.dt062g.jpaint.Main.testDrawing(Main.java:53)
at se.miun.vife1700.dt062g.jpaint.Main.main(Main.java:21)
似乎我必须编写JAXBContext context=null;在试抓之前。但我如何以不同的方式做到这一点?当我抛出异常时,程序不会继续执行吗?我不熟悉JAVA,尤其是例外情况
感谢您的任何帮助
import javax.xml.bind.*;
import java.io.File;
import java.util.Objects;
public class FileHandler {
public static void saveToXML (Drawing drawing, String fileName) {
JAXBContext context = null;
try {
context = JAXBContext.newInstance(Drawing.class);
} catch (JAXBException e) {
System.err.print("New Drawing object could not be instanced.");
}
Marshaller marshaller = null;
try {
marshaller = context.createMarshaller();
} catch (JAXBException e) {
System.err.print("Could not create a Marshaller");
}
try {
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
} catch (PropertyException e) {
System.err.print("A problem occurred when setting output format");
}
if(Objects.equals(".xml", fileName.substring(fileName.length() - 4))) {
try {
marshaller.marshal(drawing, new File(fileName));
} catch (JAXBException e) {
System.err.print("An error occurred when saving to file.");
}
}
else {
fileName += ".xml";
try {
marshaller.marshal(drawing, new File(fileName));
} catch (JAXBException e) {
System.err.print("An error occurred when saving to file.");
}
}
}
public static Drawing loadFromXML(String fileName){
Drawing drawing = null;
JAXBContext context = null;
try {
context = JAXBContext.newInstance(Drawing.class);
} catch (JAXBException e) {
System.err.print("New Drawing object could not be instanced.");
}
Unmarshaller unmarshaller = null;
try {
unmarshaller = context.createUnmarshaller();
} catch (JAXBException e) {
System.err.print("Could not create a Unmarshaller");
}
try {
drawing = (Drawing) unmarshaller.unmarshal(
new File(fileName)
);
} catch (JAXBException e) {
System.err.print("An error occurred when loading from file.");
}
return drawing;
}
}
提前谢谢
共 (0) 个答案