简体   繁体   English

在使用 RDF4J 加载和写入 TTL 文件时保留前缀

[英]Keep prefixes in loading and writing TTL file with RDF4J

I need to load a Turtle TTL file, add some triples, then save it again.我需要加载一个 Turtle TTL 文件,添加一些三元组,然后再次保存。 The original TTL file has a big header containing the prefixes for some namespaces.原始 TTL 文件有一个大的 header 包含一些命名空间的前缀。

@prefix biro: <http://purl.org/spar/biro/> .
@prefix c4o: <http://purl.org/spar/c4o/> .
@prefix dcterms: <http://purl.org/dc/terms/> .
@prefix deo: <http://purl.org/spar/deo/> .
@prefix doco: <http://purl.org/spar/doco/> .
...

After I load the file and add the triples, the saved TTL won't contain the prefixes, unless I specify them manually, one by one.在我加载文件并添加三元组之后,保存的 TTL 将不包含前缀,除非我手动指定它们,一一指定。 Is there a way to keep the namespaces already present in the loaded file?有没有办法让命名空间已经存在于加载的文件中?

This is my Java code:这是我的 Java 代码:

// Load input TTL file
InputStream stream = new FileInputStream(ttlFile);
RDFParser rdfParser = Rio.createParser(RDFFormat.TURTLE);
Model model = new LinkedHashModel();
rdfParser.setRDFHandler(new StatementCollector(model));
rdfParser.parse(stream);
stream.close();

// Code to add triples here
model.add(...);

// Save the new TTL file
FileOutputStream out = new FileOutputStream(ttlOutputFile);
RDFWriter writer = Rio.createWriter(RDFFormat.TURTLE, out);
writer.startRDF();

// Here I can add the prefixes manually
// writer.handleNamespace("dcterms", DCTERMS.NAMESPACE);

for (Statement st : model) {
    writer.handleStatement(st);
}
writer.endRDF();

Thank you for your help.谢谢您的帮助。

The problem is that your code for writing to file explicitly only writes the statements themselves, not the namespaces stored in your model object.问题是您用于显式写入文件的代码仅写入语句本身,而不是存储在model object 中的命名空间。

You could fix it by adding something like this:您可以通过添加以下内容来修复它:

model.getNamespaces().forEach(ns -> writer.handleNamespace(ns.getPrefix(), ns.getName()));

However, more generally, your code to write to file is more complex than it needs to be.但是,更一般地说,您要写入文件的代码比它需要的更复杂。 A far simpler approach to writing your model object to file would be something like this:model object 写入文件的更简单的方法是这样的:

// Save the new TTL file
FileOutputStream out = new FileOutputStream(ttlOutputFile);

Rio.write(model, out, RDFFormat.TURTLE);

or if you prefer to use a RDFWriter object (so you can tweak the config):或者如果您更喜欢使用RDFWriter object(这样您就可以调整配置):

RDFWriter writer = Rio.createWriter(out, RDFFormat.TURTLE);

//... tweak writer config

Rio.write(model, writer);

Similarly, reading the file can also be done more conveniently:同样,读取文件也可以更方便地完成:

// Load input TTL file
InputStream stream = new FileInputStream(ttlFile);
Model model = Rio.parse(stream, RDFFormat.TURTLE);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM