How to convert byte array in Base64 to Java?

Ok, I know how to do this in C #.

It's simple:

Convert.ToBase64String(byte[]) and Convert.FromBase64String(string) to get byte[] back. 

How to do it in Java?

+46
java string arrays
Mar 10 '10 at 16:14
source share
2 answers

Java 8

Encode or decode byte arrays:

 byte[] encoded = Base64.getEncoder().encode("Hello".getBytes()); println(new String(encoded)); // Outputs "SGVsbG8=" byte[] decoded = Base64.getDecoder().decode(encoded); println(new String(decoded)) // Outputs "Hello" 

Or if you just need the lines:

 String encoded = Base64.getEncoder().encodeToString("Hello".getBytes()); println(encoded); // Outputs "SGVsbG8=" String decoded = new String(Base64.getDecoder().decode(encoded.getBytes())); println(decoded) // Outputs "Hello" 

See Base64 for more information.

Java 7

Base64 is not related to Java 7. I recommend using Apache Commons Codec .

For direct byte arrays:

 Base64 codec = new Base64(); byte[] encoded = codec.encode("Hello".getBytes()); println(new String(encoded)); // Outputs "SGVsbG8=" byte[] decoded = codec.decode(encoded); println(new String(decoded)) // Outputs "Hello" 

Or if you just need the lines:

 Base64 codec = new Base64(); String encoded = codec.encodeBase64String("Hello".getBytes()); println(encoded); // Outputs "SGVsbG8=" String decoded = new String(codec.decodeBase64(encoded)); println(decoded) // Outputs "Hello" 

Android / Java 7

If you are using the Android SDK with Java 7, then the best option is to use the associated android.util.Base64 .

For direct byte arrays:

 byte[] encoded = Base64.encode("Hello".getBytes()); println(new String(encoded)) // Outputs "SGVsbG8=" byte [] decoded = Base64.decode(encoded); println(new String(decoded)) // Outputs "Hello" 

Or if you just need the lines:

 String encoded = Base64.encodeToString("Hello".getBytes()); println(encoded); // Outputs "SGVsbG8=" String decoded = new String(Base64.decode(encoded)); println(decoded) // Outputs "Hello" 
+85
Nov 05 '15 at 18:40
source share
— -

Using

 byte[] data = new Base64().decode(base64str); 

you will need to reference the commons codec from your project for this code to work.

+20
May 03 '12 at 3:50 a.m.
source share



All Articles