如何使用Apache Jena在RDF文档中编写新节点?

时间:2013-11-22 07:56:13

标签: java apache rdf jena

我想在我的RDF文档中添加新节点,这是我第一次写文档时写的:

    String eventosURI = "http://Eventos";
    String path = getServletContext().getRealPath("/") + "DataBase/Events.xml";
    Model base = ModelFactory.createDefaultModel();
    Resource node = base.createResource(eventosURI).addProperty(VCARD.NAME, something);
    try{
        FileOutputStream fos = new FileOutputStream(path);
        base.write(fos);
    } catch(Exception e){
        out.println(e.getMessage());
    }

但是我必须在同一个文档中添加更多节点,如果我调用相同的servlet重新创建模型并覆盖其他节点。

我尝试用以下方法更改FileOutputStream:

    FileWriter write = new FileWriter(path, true);
    base.write(write);

这有效但不是我想要的方式因为再次编写整个结构...有没有办法将节点添加到已经创建的RDF中?

1 个答案:

答案 0 :(得分:1)

ModelFactory.getDefaultModel()创建一个空的内存模型。如果要编辑现有模型,则需要先加载它。

你有几种方法可以做到这一点。

一个是使用Model.read(InputStream, String, String)。这将InputStream带到现有模型,图中相对URI的基URI和序列化语言(RDF / XML是默认值,它还支持TURTLE和N-TRIPLE)。该方法将所有语句添加到模型中:

Model model = ModelFactory.createDefaultModel();
if (path.exists()) {
    model.read(new FileInputStream(path), null, "TURTLE"); // or whatever format you used
}

然后,您将获得之前保存在模型中的所有陈述。