Get data from rdf file [duplicate]

2019-09-20 04:55发布

问题:

Possible Duplicate:
Java - Using Jena APi - Get data from RDF file

I'm using Java and Jena API.

I have the 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>

I'd like to get for each person the firstname, gender, date of birth and write that information in a text file. The problem I have is that it only writes the first woman/man he finds in the rdf file, but there is more than one woman and man.

Can you please explain me how can I solve this? Thank you very much.

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);
    }
}

回答1:

Your problem has nothing to do with Jena or RDF but is rather a logic error in your coding.

You call writeFile() inside your while loop which opens a new file, writes the current entry and closes the file. So you are repeatedly overwriting your file with a single entry at one time so you will only ever end up with a single person in the file.

You need to refactor the code to open the file once before the while loop, have the writeFile() method simply add to that file (and not close it) and then close the file after the while loop.

Also as @Udo Kilmaschewski pointed out in your apparent duplicate the genr variable is not defined in the code you showed so you don't appear to be correctly passing the gender from your while loop to the writeFile() function.