2

I am using JDK 1.6 and facing issue while trying to encoding/decoding French words. My code is under:

String setText = "Vos factures impayées Internet sont";
String encodedText= Base64.encode(setText.getBytes());
Base64.decode(encodedText);
System.out.println("Encoded String: " + encodedText);
byte[] result =  Base64.decode(encodedText);
String decodedString = new String(result);
System.out.println("Decoded: " + decodedString);

Result is: Original String Vos factures impayées Internet sont

Encoded String: Vm9zIGZhY3R1cmVzIGltcGF577+9ZXMgSW50ZXJuZXQgc29udA==

Decoded: Vos factures impay�es Internet sont

Issue: In decoding string i am getting " � " special character instead of "é"

Cœur
  • 37,241
  • 25
  • 195
  • 267
Touqeer
  • 87
  • 2
  • 12
  • The program actually thinks your string is `"Vos factures impay�es Internet sont"`, because your source file’s encoding does not match the file encoding assumed by the Java compiler. My guess is that you saved the file as ISO 8859-1, but the Java compiler is assuming UTF-8 (since UTF-8 is the default encoding on all non-Windows systems). Make sure you have saved your file as a UTF-8 file. – VGR Oct 24 '19 at 17:15
  • No i am not saving this in ISO 8859-1 – Touqeer Oct 28 '19 at 08:53
  • A hex dump of the `String setText = "…"` line, performed with an operating system command and not with Java code, would be quite useful. – VGR Oct 28 '19 at 11:45

1 Answers1

0

i do not have java 1.6 but try to specify encoding explicitly not to rely on platform settings, like this. maybe it will help.

String decodedString = new String(result, "UTF-8");

it will be nice if you share from which package are you using Base64and for what reasons? if you are using it with xmlanswer can differ.

George Weekson
  • 483
  • 3
  • 13
  • This is only half of the problem. The Base64 encoding represents bytes that contain an actual `�` character ([U+FFFD](http://www.fileformat.info/info/unicode/char/fffd/index.htm)) encoded in UTF-8, which indicates the problem was probably due to the encoding assumed by the compiler. Also, the StandardCharsets class was introduced in Java 1.7, so the code would need to be `new String(result, "UTF-8")`. – VGR Oct 24 '19 at 17:09
  • Having the same issue after using String decodedString = new String(result, "UTF-8"); I am using the following libraries import com.sun.org.apache.xerces.internal.impl.dv.util.Base64; import sun.misc.BASE64Encoder; I am using 1.6 JDK at client level and 1.8 at server level due to some limitations. And in the encoded string i need to pass some url like "https://google.com" – Touqeer Oct 28 '19 at 08:48
  • I'm trying with 1.8 and where I have `'�'` character in my string, where I'm using `new String(result, "UTF-8")` but still its not working, where I changed the `UTF-8` to `ISO-8859-1` and its working as expected:) – Madhusudhan Aradya Mar 02 '22 at 08:02