Java - Jena API - 输出文件 [英] Java - Jena API - Output file

查看:141
本文介绍了Java - Jena API - 输出文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Java和Jena API。

我有一个class Person ,其中的数据类型属性 hasFirstName hasLastName hasDateOfBirth hasGender



下面是在RDF文件中表示一个人的方式。

 < rdf:说明rdf:about =http://www.fam.com/FAM#Bruno04/02/1980> 
< j.0:FAMhasGender> H< /j.0:FAMhasGender>
< j.0:FAMhasDateOfBirth> 04/02/1980< /j.0:FAMhasDateOfBirth>
< j.0:FAMhasLastName> DS< /j.0:FAMhasLastName>
< j.0:FAMhasFirstName>布鲁诺< /j.0:FAMhasFirstName>
< / rdf:说明>

对于性别为女性的每个人,我想生成一个文本文件

  [label = \+ firstName +\\\\
\\\
\ D.Naiss:+ dnai1 +\,+ shape2 +]

是,例如,3女性文件必须包含3格式的格式。形状值(然后是输出行)将取决于性别,这就是为什么我不能使用同一行的两个性别。



对于每个人的性别是男性我想在下面输出这行:

  [label = \+ firstName + \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ p> 

我遇到的问题是,在输出文件中,我只能看到一个女人和一个男人与相应的行。我有不止一个女人和男人,但是他只输出一个男人和女人。这是我的问题...



以下是相关的代码:

  public void accessProp(){

readFile(inputFile); // rdf
String fname;
字符串dd;
String gen;

ExtendedIterator实例= to.person.listInstances();
个体实例= null;
个人firstInstance = null;
while(instances.hasNext()){
instance =(Individual)instances.next();

gen = instance.getPropertyValue(to.hasGender).toString();
fname = instance.getPropertyValue(to.hasFirstName).toString();
dd = instance.getPropertyValue(to.hasDateOfBirth).toString();

writeFile(fname,dd,genr);



//写入文本文件
public void writeFile(String fn,String dbir,String gn){
String fileout =D :/file1.txt;
字符串firstName = fn;
String dateB = dbir;
String gender = gn;

BufferedWriter out;
try {
out = new BufferedWriter(new FileWriter(fileout,true));

if(gender.equals(F)){
out.write([label = \+ firstName +\\\\
\\\
\\ D.Naiss:+ dnai1 +\,+ shape +]);
} else if(gender.equals(M)){
out.write([label = \+ firstName +\\\\
\\\
\ D.Naiss:+ dnai1 +\,+ shape2 +]);
}

out.newLine();

//刷新并关闭流
out.close();
catch(IOException e){
System.out.println(有问题:+ e);






$ b

你能告诉我应该修改什么来解决我的问题吗?问题?



谢谢

解决方案

完全不了解RDF,当你无法自己弄清楚什么是错误的时候,你就会努力地在这里问一些随机问题来努力工作。这种态度没有什么不妥,但是如果你仔细阅读文档(OWL,RDF和Jena),那将会更好。



我怀疑问题不是在Java方面,而是你的本体问题(除非你能证明它不是真的)。​​



我从来没有使用RDF和Jena,但是我花了几个小时阅读文档,所以即使下面的方法可能不是做事的神圣方式,它肯定比你更好。当你无法理解某些东西的时候,随时提出问题(对我或者SO社区)。首先,让我们用OWL编写我们的本体(我是新来的,所以这可能包含错误)注意:在每个程序运行中,您都不应该使用Java代码构建本体。可能你会加载你的本体从一些序列化的形式,如下所示

 <?xml version =1.0 >?; 
<! - 见http://www.w3.org/TR/2004/REC-owl-guide-20040210/#Namespaces - >
<!DOCTYPE rdf:RDF [
<!ENTITY famhttp://zybnet.com/fam#>
<!ENTITY xsdhttp://www.w3.org/2001/XMLSchema#>
]>
xmlns:rdf =http://www.w3.org/1999/02/22-rdf-syntax-ns#
xmlns:rdfs = http://www.w3.org/2000/01/rdf-schema#
xmlns:owl =http://www.w3.org/2002/07/owl#
xmlns :XSD = &安培; XSD;

xmlns =& fam;
xmlns:fam =& fam;
xml:base =& fam; >


<! - 属性名称,性别和出生 - >
< / owl:DatatypeProperty>
< / owl:DatatypeProperty>
< / owl:DatatypeProperty>

< fam:name> Bruno< / fam:name>
< fam:birth> 19/08/1987< / fam:birth>
< / rdf:说明>
< fam:name> Raffaele< / fam:name>
< fam:birth> 09/02/1927< / fam:birth>
< / rdf:说明>
< fam:name> Angela< / fam:name>
< fam:gender> F< / fam:gender>
< fam:birth> 01/06/1957< / fam:birth>
< / rdf:说明>
< / rdf:RDF>

然后是Java代码

public static void main(String [] args){
Model model = ModelFactory.createOntologyModel();
model.read(RDF.class.getResourceAsStream(family.rdf),null);

System.out.println(文件中的所有三元组);
$ b $ outQuery(SELECT?subject?predicate?object+
WHERE {?subject?predicate?object},model);

System.out.println(简单查询);
$ b $ outQuery(SELECT?subject?name?gender+
WHERE {+
?subject< http://zybnet.com/fam#name> ?+
?subject< http://zybnet.com/fam#gender> gender。+
},model);


private static void outQuery(String q,Model model){
Query query = QueryFactory.create(q);
QueryExecution execution = QueryExecutionFactory.create(query,model);
ResultSet results = execution.execSelect();
ResultSetFormatter.out(System.out,results,query);
execution.close();





$ p $最后一点log4j配置(这个必须放在classpath的 log4j.properties 中,或者从Java代码加载 PropertyConfigurator.configure

  log4j.logger.com.hp.hpl.jena =调试控制台

log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender。 console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern = [% - 5p]%m%n

这应该是您的开始代码。通过运行这个,你会看到发生了什么事情。通过理解这些代码,你将能够重构你的应用程序,并找到要学习的东西来启动和运行。祝你好运!



示例输出:(简短的文字删除)

<$ p $
一个简单的查询
[DEBUG]锁:main
------------ -------------------------------------------
| uri |名字|性别|
============================================== =========
| < HTTP://zybnet.com/user/9230> | 安吉拉| F|
| < HTTP://zybnet.com/user/0239> | Raffaele| M|
| < HTTP://zybnet.com/user/0001> | 布鲁诺| M|
---------------------------------------------- ---------


I'm using Java and Jena API.

I have a class Person with the datatype properties hasFirstName, hasLastName, hasDateOfBirth, hasGender.

Here is how one person is represented in my RDF file.

<rdf:Description rdf:about="http://www.fam.com/FAM#Bruno04/02/1980 ">
    <j.0:FAMhasGender>H</j.0:FAMhasGender>
    <j.0:FAMhasDateOfBirth>04/02/1980</j.0:FAMhasDateOfBirth>
    <j.0:FAMhasLastName>DS </j.0:FAMhasLastName>
    <j.0:FAMhasFirstName> Bruno</j.0:FAMhasFirstName>
 </rdf:Description>

For each person whose gender is female I want to generate a text file with this line below:

[label= \"" +firstName+ " \"\n\n\"D.Naiss:"+dnai1+"\", "+shape2+"]

so if there is, for example, 3 females the file must contain 3 lines with that format. The shape value( and then the output line) will depend on the gender, that's why i cannot not use the same line for both genders.

For each person whose gender is male I want to output this line below:

[label= \"" +firstName+ " \"\n\n\"D.Naiss:"+dnai1+"\", "+**shape**+"]

The problem I have is that in the output file i only see one woman and one man with the corresponding line. I have more than one woman and man but he only outputs one for each gender. That's my problem...

Here is the relevant code:

public void accessProp() {

    readFile(inputFile); // rdf
    String fname;
    String dd;
    String gen;

    ExtendedIterator instances = onto.person.listInstances();
    Individual instance = null;
    Individual firstInstance = null;
    while (instances.hasNext()) {
        instance = (Individual) instances.next();

        gen = instance.getPropertyValue(onto.hasGender).toString();
        fname = instance.getPropertyValue(onto.hasFirstName).toString();
        dd = instance.getPropertyValue(onto.hasDateOfBirth).toString();

        writeFile(fname, dd, genr);
    }
}

// Write text file
public void writeFile(String fn, String dbir, String gn) {
    String fileout = "D:/file1.txt";
    String firstName = fn;
    String dateB = dbir;
    String gender = gn;

    BufferedWriter out;
    try {
        out = new BufferedWriter(new FileWriter(fileout, true));

        if (gender.equals("F")) {
            out.write("[label= \"" + firstName + " \"\n\n\"D.Naiss:" + dnai1 + "\", " + shape + "]");
        } else if (gender.equals("M")) {
            out.write("[label= \"" + firstName + " \"\n\n\"D.Naiss:" + dnai1 + "\", " + shape2 + "]");
        }

        out.newLine();

        // flushes and closes the stream
        out.close();
    } catch (IOException e) {
        System.out.println("There was a problem:" + e);
    }
}

Can you tell me what should I modify to solve my problem?

Thanks

解决方案

Is my humble opinion that you don't know RDF altogether, and your are struggling to get things working by asking random questions here on SO when you are not able to figure out what's wrong by yourself. There's nothing wrong with this attitude, however it would be way better if you tried to carefully read the documentation (OWL, RDF and Jena).

I suspect that the problem is not on the Java side, but instead it's an issue with your ontology (unless you can prove it's not true).

I never used RDF and Jena at all, however I spent a couple of hours reading the docs, so even if the following may not be the holy way to do things, it's certainly a way better than yours. Feel free to ask questions (to me or to the SO community) when you can't understand something. First, let's write our ontology in OWL (I'm new to this, so this may contain errors) Note: You are not supposed to build your ontology in Java code at every program run. Likely you'll load your ontology from some serialized form like the following

<?xml version="1.0"?>
<!-- See http://www.w3.org/TR/2004/REC-owl-guide-20040210/#Namespaces -->
<!DOCTYPE rdf:RDF [
<!ENTITY fam "http://zybnet.com/fam#" >
<!ENTITY xsd "http://www.w3.org/2001/XMLSchema#" >
]>
<rdf:RDF
    xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
    xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
    xmlns:owl="http://www.w3.org/2002/07/owl#"
    xmlns:xsd="&xsd;"

    xmlns    ="&fam;" 
    xmlns:fam="&fam;" 
    xml:base ="&fam;" >

    <owl:Class rdf:about="Person" />

    <!-- Properties name, gender, and birth -->
    <owl:DatatypeProperty rdf:about="&fam;name">
        <rdfs:domain rdf:resource="Person" />
        <rdfs:range  rdf:resource="&xsd;string" />
    </owl:DatatypeProperty>
    <owl:DatatypeProperty rdf:about="&fam;birth">
        <rdfs:domain rdf:resource="Person" />
        <rdfs:range  rdf:resource="&xsd;date" />
    </owl:DatatypeProperty>
    <owl:DatatypeProperty rdf:about="&fam;gender">
        <rdfs:domain rdf:resource="Person" />
        <rdfs:range  rdf:resource="&xsd;string"/>
    </owl:DatatypeProperty>

    <rdf:Description rdf:about="user/7192">
        <fam:name>Bruno</fam:name>
        <fam:gender>M</fam:gender>
        <fam:birth>19/08/1987</fam:birth>
    </rdf:Description>
    <rdf:Description rdf:about="user/3023">
        <fam:name>Raffaele</fam:name>
        <fam:gender>M</fam:gender>
        <fam:birth>09/02/1927</fam:birth>
    </rdf:Description>
    <rdf:Description rdf:about="user/9283">
        <fam:name>Angela</fam:name>
        <fam:gender>F</fam:gender>
        <fam:birth>01/06/1957</fam:birth>
    </rdf:Description>
</rdf:RDF>

Then comes the Java code

public class RDF {
    public static void main(String[] args) {
        Model model = ModelFactory.createOntologyModel();
        model.read(RDF.class.getResourceAsStream("family.rdf"), null);

        System.out.println("All triples in file");

        outQuery("SELECT ?subject ?predicate ?object " +
                "WHERE { ?subject ?predicate ?object }", model);

        System.out.println("A simple query");

        outQuery("SELECT ?subject ?name ?gender " +
                "WHERE { " +
                " ?subject <http://zybnet.com/fam#name> ?name ." +
                " ?subject <http://zybnet.com/fam#gender> ?gender ." +
                " }", model);
    }

    private static void outQuery(String q, Model model) {
        Query query = QueryFactory.create(q);
        QueryExecution execution = QueryExecutionFactory.create(query, model);
        ResultSet results = execution.execSelect();
        ResultSetFormatter.out(System.out, results, query);
        execution.close();
    }

}

And finally a bit of log4j configuration (this must be put in a log4j.properties on the classpath, or loaded from Java code with PropertyConfigurator.configure)

log4j.logger.com.hp.hpl.jena=debug, console

log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%-5p] %m%n

This should be your starting code. By running this, you'll see what's going on. By understanding this code, you'll be able to refactor your application and find ouy what to study to get it up and running. Good luck!

Sample output: (text removed from brevity)

[Lots of text here...]
A simple query
[DEBUG] Lock : main
-------------------------------------------------------
| uri                           | name       | gender |
=======================================================
| <http://zybnet.com/user/9230> | "Angela"   | "F"    |
| <http://zybnet.com/user/0239> | "Raffaele" | "M"    |
| <http://zybnet.com/user/0001> | "Bruno"    | "M"    |
-------------------------------------------------------

这篇关于Java - Jena API - 输出文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆