how to decode the string from Base64 to UTF-8 in java
I have string in base64 format and i want decode it to utf-8 and can anyone help me on this?
how to decode the string from Base64 to UTF-8 in java
I have string in base64 format and i want decode it to utf-8 and can anyone help me on this?
As zatenzu mentioned in a comment to the original post, this question has already been answered.
However, that question is old, and the answers that have been most upvoted point to solutions that are not available in java "out-of-the-box", and require additional libraries.
So, I would like to add that as of java 8 there is a java.util.Base64
class which you can use for conversions to and from base64.
See: http://docs.oracle.com/javase/8/docs/api/java/util/Base64.html
There are several available implementations of BASE64.
First is a part of java SDK: sun.misc.Base64Decoder
. You can use it without any external dependencies. Disadvantage of using this class is that it is not recommended to use classes from package sun.*
, com.sun.*
etc since they are not for application level usage and theoretically can be changed without any notice.
Other more or less standard implementations are
javax.xml.bind.DatatypeConverter
, org.apache.commons.codec.binary.Base64
etc that require external dependencies.
Google Guava is a good choice,
POM config:
<dependency>
<artifactId>guava</artifactId>
<groupId>com.google.guava</groupId>
<type>jar</type>
<version>14.0.1</version>
</dependency>
Sample code:
String inputContent = "Hello Việt Nam";
String base64String = BaseEncoding.base64().encode(inputContent.getBytes("UTF-8"));
//decode
System.out.println("Base64:" + base64String);//SGVsbG8gVmnhu4d0IE5hbQ==
byte[] contentInBytes = BaseEncoding.base64().decode(base64String);
System.out.println("Source content: " + new String(contentInBytes, "UTF-8"));//Hello Việt Nam