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.