Java - Jena API - Output file

最后都变了- 提交于 2019-12-13 14:43:05

问题


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


回答1:


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"    |
-------------------------------------------------------



回答2:


You close your output file in writeFile so no more data can be written after the first invocation of this method. Close the file after your main loop in accessProp.



来源:https://stackoverflow.com/questions/12236195/java-jena-api-output-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!