如何在.nt文件中保存sparql查询的结果

时间:2011-06-26 13:16:22

标签: java rdf sparql nt

我想在N-Triple文件(.nt文件)上保存dbpedia个电影的所有三元组,我使用java应用程序在dbpedia端点上查询并将结果保存到文件中,但我可以不读取此文件并从中获取查询!你帮帮我吗?

//我保存结果的代码在这里

try{
            FileWriter fostream = new FileWriter("C:\\Documents and Settings\\me\\Desktop\\DataSets\\dbpediafilmdataset.nt");
            BufferedWriter out = new BufferedWriter(fostream);
            String service ="http://dbpedia.org/sparql";

            String query = 
            "SELECT ?s ?p ?o " +
            "WHERE {" +
            " ?s <http://dbpedia.org/property/wordnet_type> <http://www.w3.org/2006/03/wn/wn20/instances/synset-movie-noun-1> ; ?p ?o "+
            "      } ";

            QueryExecution qexecctest = QueryExecutionFactory.sparqlService(service, query);

            try {
            ResultSet responseetest = qexecctest.execSelect();

            while( responseetest.hasNext()){
                QuerySolution solnntest = responseetest.nextSolution();
                RDFNode p = solnntest.get("?p");
                RDFNode o = solnntest.get("?o");
                RDFNode s = solnntest.get("?s");
                String object="";
                String triple="";
                if (o.isLiteral()==true)
                {
                    object="\"" + o.toString() + "\"";
                }
                else
                object="<" + o.toString() + ">";

                triple="<" + s + ">"+" " + "<" + p + ">" + " " + object + " " + "." ;

                out.write(triple);
                out.newLine();

                }
            } finally {
            qexecctest.close();
            out.close();}

            }catch (Exception e){
              System.err.println("Error: " + e.getMessage());}

当我想读取结果文件并从中获取查询时,它会出现如下错误:

com.hp.hpl.jena.rdf.model.impl.IStream.readChar(NTripleReader.java:485)
com.hp.hpl.jena.rdf.model.impl.NTripleReader.unwrappedReadRDF(NTripleReader.java:140)
com.hp.hpl.jena.rdf.model.impl.NTripleReader.readRDF(NTripleReader.java:120)
com.hp.hpl.jena.rdf.model.impl.NTripleReader.read(NTripleReader.java:84)
com.hp.hpl.jena.rdf.model.impl.NTripleReader.read(NTripleReader.java:72)
com.hp.hpl.jena.rdf.model.impl.ModelCom.read(ModelCom.java:226)
com.hp.hpl.jena.util.FileManager.readModelWorker(FileManager.java:395)
com.hp.hpl.jena.util.FileManager.readModel(FileManager.java:335)
com.hp.hpl.jena.util.FileManager.readModel(FileManager.java:319)
....

1 个答案:

答案 0 :(得分:3)

最好使用CONSTRUCT查询执行此操作。看看它,它是专门为此目的而设计的。 Jena只需要做一些事情:

Model results = qexec.execConstruct();
results.write(out, "TURTLE");

还解释了here

主要的优点是你不必担心用Turtle或任何其他格式编写三元组,Jena会为你做这件事。

您的CONSTRUCT查询可能最终看起来像:

CONSTRUCT { ?s ?p ?o }
WHERE {
    ?s <http://dbpedia.org/property/wordnet_type>        
         <http://www.w3.org/2006/03/wn/wn20/instances/synset-movie-noun-1> ; 
         ?p ?o 
}