

This is necessary to finalize the encoded data line. encodingStream.write(bytes) ĭon't forget to close the stream when the writing operation is completed. Data will be automatically encoded by the Base64OutputStream class.

Now you can write your bytes in the stream as you would do with a common output stream. you can send encoded data directly to a file by calling: Base64OutputStream encodingStream = new Base64OutputStream(new FileOutputStream("encoded.b64")) You can create a Base64OutputStream by wrapping another existing OutputStream: Base64OutputStream encodingStream = new Base64OutputStream(myOutputStream) The Base64OutputStream extends java.io.OutputStream and works as many other well know Java streams. You can gain more control on the encoding process by avoiding the use of the static utilities in the Base64 class and by using directly a it.sauronsoftware.base64. Encoding from a file to another: File source = new File("source.jpg") ĭecoding from a file to another: File encoded = new File("encoded.b64") īcode(encoded, decoded) Encoding with Base64OutputStream Shortcuts for java.io.File objects are provided. OutputStream outputStream = new FileOutputStream("decoded.jpg") īcode(inputStream, outputStream) In similar manner, a stream can be decoded: InputStream inputStream = new FileInputStream("encoded.b64") OutputStream outputStream = new FileOutputStream("encoded.b64") īase64.encode(inputStream, outputStream)
Base64 decode string to string java code#
The next sample code encodes a file to another, using java.io.InputStream and java.io.OutputStream objects: InputStream inputStream = new FileInputStream("source.jpg") Larger data are better handled with streams. If data are not large and you handle them directly in memory, using a byte array: byte source =. images) you can use other forms of the encode() and decode() methods. If you are working with binary data (i.e. You can force the use of a specific charset during strings encoding and decoding operations: String encoded = Base64.encode("Hello, world!", "UTF-8") The result of this operation is a Base64 encoded string, that you can decode back later by calling: String decoded = code(encoded) If you want to encode a string, you can easily call: String encoded = Base64.encode("Hello, world!") Base64 utility class is, in most of cases, has everything you need to encode and decode.įirst of all, you should tell apart if you have to encode/decode a string or a binary stream. The javabase64 library consists of two streams and a utility class. InstallationĪdd the javabase64-1.3.jar file to your application classpath, and you'll beĪutomatically enabled to the use of the javabase64 classes. To run the javabase64 library you need a Java Runtime Environment J2SE v.
