从项目目录java

时间:2018-05-20 18:50:55

标签: java xml file nullpointerexception

我的项目文件夹中有一个xml文件(Bitacora.xml),如下所示:

xml inside project folder

该文件的内容是:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE xml>
<bitacora>
    <log>
        <fecha>2018/05/20</fecha>
        <hora>11:05:44</hora>
        <accion>Probando</accion>
    </log>
</bitacora>

我想阅读内容以添加新节点。但每次我运行它,它都会给我一个NullPointerExcpetion这样的:

Exception in thread "main" java.lang.NullPointerException at pruebaFacebookCalls.principal.main(principal.java:39)

这是我的代码:

DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

    ClassLoader cl = new principal().getClass().getClassLoader();
    File file;
    file = new File(cl.getResource("./Bitacora.xml").getFile());

    Document document = documentBuilder.parse(file);
    Element root = document.getDocumentElement();
    Element rootElement = document.getDocumentElement();

    Element log = document.createElement("log");
    rootElement.appendChild(log);

    Element fecha = document.createElement("fecha");
    fecha.appendChild(document.createTextNode(dtf.format(localDate).toString()));
    log.appendChild(fecha);

    Element hora = document.createElement("hora");
    hora.appendChild(document.createTextNode(LocalDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss"))));
    log.appendChild(hora);

    Element accion = document.createElement("accion");
    accion.appendChild(document.createTextNode("TESTING ACTION"));
    log.appendChild(accion);

    root.appendChild(log);

    DOMSource source = new DOMSource(document);

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    StreamResult result = new StreamResult("Bitacora.xml");
    transformer.transform(source, result);

我不明白为什么找不到文件,我必须在哪里放置我的xml文件才能让代码找到它?

1 个答案:

答案 0 :(得分:0)

在您的代码中,对cl.getResource("./Bitacora.xml")的调用会返回null,而这会在传递此空值时导致NullPointerException

您可以使用

打开xml文件
ClassLoader cl = new principal().getClass().getClassLoader();
URL res = cl.getResource("pruebaFacebookCalls/Bitacora.xml");
// also, why not print out the location your resource
System.out.println("resource found at url="+res);
InputStream is = res.openStream();
Document document = documentBuilder.parse(is);
// etc..
// etc..
//and remember to close the stream when finished,
is.close();