String s = "String to encode/decode in Base64 with DataTypeConverter"; String coded = DatatypeConverter.printBase64Binary(s.getBytes()); byte[] retr = DatatypeConverter.parseBase64Binary(coded); System.out.println("Coded : " + coded); System.out.println("Expected : " + s); System.out.println("Retrieved : " + new String(retr)); System.out.println();
Coded : U3RyaW5nIHRvIGVuY29kZS9kZWNvZGUgaW4gQmFzZTY0IHdpdGggRGF0YVR5cGVDb252ZXJ0ZXI= Expected : String to encode/decode in Base64 with DataTypeConverter Retrieved : String to encode/decode in Base64 with DataTypeConverter
For input/output streams, one can use the following:
String s = "String to encode/decode in Base64 using streams"; ByteArrayOutputStream collect = new ByteArrayOutputStream(); Base64OutputStream b64os = new Base64OutputStream(collect); b64os.write(s.getBytes()); b64os.close(); byte[] ba = collect.toByteArray(); String coded = new String(ba); InputStream is = new ByteArrayInputStream(ba); Base64InputStream b64is = new Base64InputStream(is); byte[] retr = IOUtils.toByteArray(b64is); System.out.println("Coded : " + coded); System.out.println("Expected : " + s); System.out.println("Retrieved : " + new String(retr));
Coded : U3RyaW5nIHRvIGVuY29kZS9kZWNvZGUgaW4gQmFzZTY0IHVzaW5nIHN0cmVhbXM= Expected : String to encode/decode in Base64 using streams Retrieved : String to encode/decode in Base64 using streams
More Java tips & tricks here.
No comments:
Post a Comment