我有一个类将输出我的对象到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;
}
}
提前致谢 .