简体   繁体   中英

write result of SPARQL to file in java

I use fuseki server as embedded server in java and I get SPARQL results with following piece of code:

public static void execSelectAndPrint(FileWriter fw, String serviceURI, String query) throws IOException {
    QueryExecution q = QueryExecutionFactory.sparqlService(serviceURI,query);
    ResultSet results = q.execSelect();
    ResultSetFormatter.outputAsCSV(System.out, results);
    while (results.hasNext()) {
        QuerySolution soln = results.nextSolution();
        RDFNode x = soln.get("x");
        System.out.println(x);
        fw.append(x.toString());        
    }
    fw.close();
}

it prints results to console correctly but it can write to file. I want to write result of SPARQL query to a csv file.

Java Writer s can produce problems with character translation which is why the API prefers OutputStream and so using FileOutputStream will work.

Otherwise, output to bytes using ByteArrayOutputStream , convert to a string and write the string.

But be careful about character sets. Most SPARQL related formats are UTF-8, not the platform native character set.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM