Jena result in UTF-8 format
How can I get in Jena (Java language) result in UTF-8 format? My code:
Query query= QueryFactory.create(queryString);
QueryExecution qexec= QueryExecutionFactory.sparqlService("http://lod.openlinksw.com开发者_JAVA技巧/sparql", queryString);
ResultSet results = qexec.execSelect();
List<QuerySolution> list = ResultSetFormatter.toList(results);
System.out.println(list.get(i).get("churchname"));
I assume this is related to UTF-8 formatting in SPARQL?
Having looked at it here's what's happened:
- Importer took input 'Chodovská tvrz' encoded in utf-8.
- In utf-8 that's: '43 68 6f 64 6f 76 73 6b c3 a1 20 74 76 72 7a' (c3 a1 is 'á' in utf-8)
- Importer read those bytes instead as unicode characters.
- So instead of 'á' you get the two characters c3 a1, which are 'Ã' and '¡'.
You can reverse that by turning the characters of the string to a byte array, then making a new string from it. I'm sure there must be a simpler way, but here's an example:
public class Convert
{
public static void main(String... args) throws Exception {
String in = "Chodovsk\u00C3\u00A1 tvrz";
char[] chars = in.toCharArray();
// make a new string by treating chars as bytes
String out = new String(fix(chars), "utf-8");
System.err.println("Got: " + out); // Chodovská tvrz
}
public static byte[] fix(char[] a) {
byte[] b = new byte[a.length];
for (int i = 0; i < a.length; i++) b[i] = (byte) a[i];
return b;
}
}
Using this on list.get(i).get("churchname").toString()
(which is what you are printing) will fix those names.
Edit:
Or just use:
String churchname = list.get(i).get("churchname").toString();
String out2 = new String(churchname.getBytes("iso-8859-1"), "utf-8");
Which is much simpler.
精彩评论