java jaxb注解xmlnull_在Java中创建新的JAXBContext实例时出现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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值