Skip to content

Instantly share code, notes, and snippets.

@dmhendricks
Created October 15, 2019 19:07
Show Gist options
  • Save dmhendricks/0540f301d3d4e2dad9fc47e467e9489a to your computer and use it in GitHub Desktop.
Save dmhendricks/0540f301d3d4e2dad9fc47e467e9489a to your computer and use it in GitHub Desktop.
Base64 encode / decode strings in Java (examples)
/**
* Because searching for a simple example of how to Base64 encode/decode in Java
* that hasn't been deprecated since the Crimean War is an exercise in madness...
*
* Requires Java 8 or higher
*/
package hn.daniel;
import java.util.Base64;
public class HelloDarknessMyOldFriend {
public static void main(String[] args) {
// Input string
String originalString = "Hello World!";
System.out.println("Original String: " + originalString);
// Encoded string
String encodedString = Base64.getEncoder().encodeToString(originalString.getBytes());
System.out.println("Encoded String: " + encodedString);
// Decoded string
byte[] decodedBytes = Base64.getDecoder().decode(encodedString);
String decodedString = new String(decodedBytes);
System.out.println("Decoded String: " + decodedString);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment