jena解析rdf、nt、ttl格式数据

来源:互联网 发布:多点触摸软件 编辑:程序博客网 时间:2024/05/18 14:46
import java.io.InputStream;import com.hp.hpl.jena.rdf.model.Model;import com.hp.hpl.jena.rdf.model.ModelFactory;import com.hp.hpl.jena.rdf.model.RDFNode;import com.hp.hpl.jena.rdf.model.Resource;import com.hp.hpl.jena.rdf.model.Statement;import com.hp.hpl.jena.rdf.model.StmtIterator;import com.hp.hpl.jena.util.FileManager;public class test{public static void main(String args[]){//String inputFileName = "E:\\Pattern Mining\\test.rdf";String inputFileName = "E:\\Pattern Mining\\test.nt";//String inputFileName = "E:\\Pattern Mining\\test.ttl";Model model = ModelFactory.createDefaultModel();InputStream in = FileManager.get().open(inputFileName);if (in == null) {throw new IllegalArgumentException("File: " + inputFileName + " not found");}//model.read(in, "","RDF/XML");//根据文件格式选用参数即可解析不同类型model.read(in, "","N3");//model.read(in, "","TTL");// list the statements in the graphStmtIterator iter = model.listStatements();// print out the predicate, subject and object of each statementwhile (iter.hasNext()) {Statement stmt = iter.nextStatement(); // get next statement//Resource subject = stmt.getSubject(); // get the subject//Property predicate = stmt.getPredicate(); // get the predicate//RDFNode object = stmt.getObject(); // get the objectString subject = stmt.getSubject().toString(); // get the subjectString predicate = stmt.getPredicate().toString(); // get the predicateRDFNode object = stmt.getObject(); // get the objectSystem.out.print("主语 " + subject);System.out.print(" 谓语 " + predicate);if (object instanceof Resource) {System.out.print(" 宾语 " + object);}else {// object is a literalSystem.out.print("宾语 \"" + object.toString() + "\"");}System.out.println(" ."); }}}