Converting % encoded characters to "normal" values
I am reading text files (RDF) using the NxParser library.
I am getting lots of 'percent encoded' characters. My question is two fold:
Should I save the words with the encoding and 'decode' them when I want to di开发者_如何学编程splay them, or should I decode them and then store them (I am using MySQL to store data (if that makes any difference))
How do I decode the reserved characters, I've been trying to find a library that can take some input and then print out a 'nice' version of the same word
I have tried replacing some of the characters with their 'normal' equivalent like so someString.replaceAll("%28","(").replaceAll("%29",")
. This works fine, but of course it's time consuming to write and perhaps slow to run as well (if lots of replaceAll() are called).
I think you want to use the java.net.URLDecoder to decode the % encoded elements. The complement to this of course is java.net.URLEncoder which encodes special characters to % elements.
Should I save the words with the encoding and 'decode' them when I want to display them [...]?
I would save them "unencoded" and encode them when you want to display them. (Different (future?) display mechanisms may require different encodings!)
How do I decode the reserved characters, I've been trying to find a library that can take some input and then print out a 'nice' version of the same word
You should use URLDecoder
for this purpose.
Example:
System.out.println(URLDecoder.decode("Hello %28 world", "UTF-8"));
Output:
Hello ( world
You have a "URL encoded" string. Try this:
import java.net.URLDecoder;
String someString = "%28test%29";
String decoded = URLDecoder.decode(url, "UTF-8");
System.out.println(decoded); // "(test,"
- It would be best to save the decoded values.
Since your values are stored in a database there is no need to keep them encoded. It would be clearer to have the actual decoded values instead of the less readable encoded versions. Depending on the requirement, you can encode these values again before using them somewhere. - Use java.net.URLDecoder to decode these values
精彩评论