I have to handle this scenario in Java:
I'm getting a request in XML form from a client with declared encoding=utf-8. Unfortunately it may contain not utf-8 characters and there is a requirement to remove these characters from the xml on my side (legacy).
Let's consider an example where this invalid XML contains £ (pound).
1) I get xml as java String with £ in it (I don't have access to interface right now, but I probably get xml as a java String). Can I use replaceAll(£, "") to get rid of this character? Any potential issues?
2) I get xml as an array of bytes - how to handle this operation safely in that case?
This code removes all 4-byte utf8 chars from string.This can be needed for some purposes while doing Mysql innodb varchar entry
Once you convert the byte array to String on the java machine, you'll get (by default on most machines) UTF-16 encoded string. The proper solution to get rid of non UTF-8 characters is with the following code:
or if you want to validate if some string contains non utf8 characters you would use Pattern.matches like:
If you have the byte array available than you could filter them even more properly with:
For making a whole web app be UTF8 compatible read here:
How to get UTF-8 working in Java webapps
More on Byte Encodings and Strings.
You can check your pattern here.
The same in PHP here.
I am assuming that you rather mean that you want to get rid of non-ASCII characters, because you're talking about a "legacy" side. You can get rid of anything outside the printable ASCII range using the following regex:
You need to wrap the
byte[]
in anByteArrayInputStream
, so that you can read them in an UTF-8 encoded character stream usingInputStreamReader
wherein you specify the encoding and then use aBufferedReader
to read it line by line.E.g.
UTF-8 is an encoding; Unicode is a character set. But the GBP symbol is most definitely in the Unicode character set and therefore most certainly representable in UTF-8.
If you do in fact mean UTF-8, and you are actually trying to remove byte sequences that are not the valid encoding of a character in UTF-8, then...
I faced the same problem while reading files from a local directory and tried this:
You might have to use your network input stream instead of FileInputStream.
-- Kapil
Note that the first step should be that you ask the creator of the XML (which is most likely a home grown "just print data" XML generator) to ensure that their XML is correct before sending to you. The simplest possible test if they use Windows is to ask them to view it in Internet Explorer and see the parsing error at the first offending character.
While they fix that, you can simply write a small program that change the header part to declare that the encoding is ISO-8859-1 instead:
and leave the rest untouched.