Generate RDF file in Java

In this example we are going to generate our first RDF( Resource Description File).

Generate RDF file in Java

Generate RDF file in Java

     

In this example we are going to generate our first RDF( Resource Description File). This example generates a  RDF file with the use of "Jena". Jena is a java API to create and manipulate RDF graphs.

To create RDF file we do need to import following packages:

  • "com.hp.hpl.jena.rdf.model"  : for creating and manipulating model resources.
  • "com.hp.hpl.jena.vocabulary": for creating VCARD vocabulary.

To create model we have used createDefaultModel() of ModelFactory, which in turn returns an object of Model interface. 

Model model = ModelFactory.createDefaultModel();

To create resource we have used createResource() method of Model interface. Now we can add properties in this model resource by using the "addProperty()" method.

GenerateRDF.java

import java.io.*;
import com.hp.hpl.jena.rdf.model.*;
import com.hp.hpl.jena.vocabulary.*;

public class GenerateRDF extends Object {
  public static void main (String args[]) {
  String personURI  = "http://localhost/amitkumar";
  String givenName  = "Amit";
  String familyName = "Kumar";
  String fullName = givenName+familyName;

  Model model = ModelFactory.createDefaultModel();

  Resource node = model.createResource(personURI)
 .addProperty(VCARD.FN, fullName)
 .addProperty(VCARD.N,
  model.createResource()
 .addProperty(VCARD.Given, givenName)
 .addProperty(VCARD.Family, familyName));
  model.write(System.out);
  }
}

To run the example you have to follow these steps:

  1. Create and save the code as GenerateRDF.java
  2. Add "jena.jar, icu4j_3_4.jar, iri.jar, commons-logging-1.1.1.jar, xercesImpl.jar" to your classpath.
  3. Compile GenerateRDF file and
  4. Run GenerateRDF class file

You will get following output on your command prompt.


Download Source Code