Today, someone on a mailing list I was reading asked about how to do Base64 encoding and decoding in Java. Surprisingly, it's not part of the core libraries and although there are a couple of them hidden away they're either private or not recommend for use. Usually I end up googling for an implementation I can use (which may be what you've done to find this page).

I thought that I ought to be able to make my own, so here's the result of a couple of hours of hacking around. Consider it freeware. Use it wherever you like. No warranties. If it doesn't work for you either let me know or just grab another one from the Internet...

Download

Example usage:

  String x = "To the batmobile! Atomic batteries to power. Turbines to speed.";

  // Encode, no linefeeds
  Base64.encode(x.getBytes());
  // Same as the above
  Base64.encode(x.getBytes(), false));
  // Encode, linefeed at 76 chars (MIME encoding)
  Base64.encode(x.getBytes(), true));

  // Decode
  Base64.decode( Base64.encode(x.getBytes()) );
Post a Comment:
  • HTML Syntax: NOT allowed

This blog copyright 2009 by Adam Turnbull