- Base64 Stream Examples in Java
- Reading and Writing a Base64 String Example
- Reading Base64 Data from a File Stream Example
- Reading Base64 data from a Socket InputStream
- Writing Base64 data using a ServerSocket OutputStream
- Encode a file into base64 in Java
- Java Articles
- Java file decode base64
- BASE64CARS
- REVERSEBASE64CHARS
- VERSION
Base64 Stream Examples in Java
The following examples use Apache’s Commons Codec library which is available on Maven Central by using the following dependency in your pom.xml file.
dependency> groupId>commons-codecgroupId> artifactId>commons-codecartifactId> version>1.15version> dependency>
Reading and Writing a Base64 String Example
The following code will allow you to read or decode a Base64 encoded String in Java. This is useful for data that is short or limited in length. Note that there are two steps involved in this process:
- First, we decode the data back into a binary format using the Base64 class’s decodeBase64 helper method. If your data was only binary data to begin with, you can simply use the data as it returns.
- Second, since my original data was UTF-8 encoded text I convert that binary data back into a String using Apache’s StringUtils class.
import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.StringUtils; public class Base64Example public static void main(String[] args) // An example of a Base64 encoded String String base64 = "SGVsbG8gV29ybGQhIFRoaXMgaXMgYW4gZXhhbXBsZSBvZiBCYXNlNjQgZW5jb2RlZCBkYXRhLg= token punctuation">; // Decode the Base64 String and get a byte array containing the data byte[] bytes = Base64.decodeBase64(base64); // Convert the byte array to a UTF-8 String String utf8 = StringUtils.newStringUtf8(bytes); System.out.println(utf8); > >
Reading Base64 Data from a File Stream Example
The following code uses Apache’s Base64InputStream to read base64 data and decode it in a conventional stream type of format.
This is useful for decoding large amounts of Base64 encoded data or used within processes where data is consumed using a stream. You can simply wrap a FileInputStream with the Base64InputStream so base64 data is automatically decoded as you consume bytes from an InputStream.
// An example of a Base64 encoded String String base64 = "SGVsbG8gV29ybGQhIFRoaXMgaXMgYW4gZXhhbXBsZSBvZiBCYXNlNjQgZW5jb2RlZCBkYXRhLg= token punctuation">; // Write our Base64 String into a text file try (FileWriter fileWriter = new FileWriter("base64.txt")) fileWriter.write(base64); > // Use Apache's Base64InputStream to read the data in from our file try (Scanner scanner = new Scanner(new Base64InputStream(new FileInputStream("base64.txt")))) while (scanner.hasNextLine()) // Print the line to the console System.out.println(scanner.nextLine()); > >
Reading Base64 data from a Socket InputStream
The following code can be used in tandem with the next section’s code on using a ServerSocket to write data. Simply run this codebase after starting the following server socket code.
We can even wrap a Java Socket’s InputStream with a Base64InputStream so that all of the data is sent over the network encoded in base64 format.
- This is sometimes helpful when writing binary data to a socket that also sends zero or null byte terminated-strings. This way the low bytes of the binary data do not interfere with the newline or zero byte characters of the stream.
- Additionally, this can be useful when attempting to send encrypted data over a socket in the same fashion, as what was originally a String is changed to bytes ranging from 0-255.
import org.apache.commons.codec.binary.Base64InputStream; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; import java.util.Scanner; public class SocketReadBase64 public static void main(String[] args) throws IOException Socket socket = new Socket(); // Connect to our server (localhost, port 5555) socket.connect(new InetSocketAddress("0.0.0.0", 5555)); // Wrap our Socket's InputStream with a Base64 InputStream try (Scanner scanner = new Scanner(new Base64InputStream(socket.getInputStream()))) while (scanner.hasNextLine()) // Print the line to the console System.out.println(scanner.nextLine()); > > > >
Writing Base64 data using a ServerSocket OutputStream
The following code reads a Base64 Encoded file on the disk (decoding it in the process) and then re-encodes the file into base64, writing those bytes to the first socket connection the ServerSocket receives.
import org.apache.commons.codec.binary.Base64InputStream; import org.apache.commons.codec.binary.Base64OutputStream; import java.io.FileInputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; public class ServerSocketBase64 public static void main(String[] args) throws IOException ServerSocket server = new ServerSocket(5555); Socket socket = server.accept(); // Wrap the socket channel's OutputStream with a Base64OutputStream so data can be written back out in Base64 try (Base64OutputStream base64OutputStream = new Base64OutputStream(socket.getOutputStream())) // Read and decode our base64 data file with a Base64InputStream wrapping a FileInputStream try (Base64InputStream base64InputStream = new Base64InputStream(new FileInputStream("base64.txt"))) // Write a single byte at a time to our outputstream. This can be further improved by using a buffer for (int data = base64InputStream.read(); data != -1; data = base64InputStream.read()) base64OutputStream.write(data); > > > > >
Encode a file into base64 in Java
For comparison, here is how to encode a file into base64 without using streams. Note this will not scale well as it can consume large amounts of memory if you are converting a large file.
import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.util.Base64; public class Base64Example public static void main(String[] args) throws IOException // Read the file into a byte array using try with resources File file = new File("path/to/file.txt"); byte[] data = new byte[(int) file.length()]; try (FileInputStream fis = new FileInputStream(file)) fis.read(data); > // Encode the byte array into base64 String encoded = Base64.getEncoder().encodeToString(data); // Write the encoded base64 string to a file File outputFile = new File("path/to/output.txt"); try (FileWriter fw = new FileWriter(outputFile)) fw.write(encoded); > > >
Java Articles
See more of my articles on Java:
Java file decode base64
Implements Base64 encoding and decoding as defined by RFC 2045: «Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies» page 23.
The Base64 Content-Transfer-Encoding is designed to represent arbitrary sequences of octets in a form that need not be humanly readable. The encoding and decoding algorithms are simple, but the encoded data are consistently only about 33 percent larger than the unencoded data. This encoding is virtually identical to the one used in Privacy Enhanced Mail (PEM) applications, as defined in RFC 1421.
A 65-character subset of US-ASCII is used, enabling 6 bits to be represented per printable character. (The extra 65th character, » .», CR, LF) and to the multipart boundary delimiters defined in RFC 2046 (e.g., «-«).
Table 1: The Base64 Alphabet Value Encoding Value Encoding Value Encoding Value Encoding 0 A 17 R 34 i 51 z 1 B 18 S 35 j 52 0 2 C 19 T 36 k 53 1 3 D 20 U 37 l 54 2 4 E 21 V 38 m 55 3 5 F 22 W 39 n 56 4 6 G 23 X 40 o 57 5 7 H 24 Y 41 p 58 6 8 I 25 Z 42 q 59 7 9 J 26 a 43 r 60 8 10 K 27 b 44 s 61 9 11 L 28 c 45 t 62 + 12 M 29 d 46 u 63 / 13 N 30 e 47 v 14 O 31 f 48 w (pad) = 15 P 32 g 49 x 16 Q 33 h 50 y
The encoded output stream must be represented in lines of no more than 76 characters each. All line breaks or other characters no found in Table 1 must be ignored by decoding software. In base64 data, characters other than those in Table 1, line breaks, and other white space probably indicate a transmission error, about which a warning message or even a message rejection might be appropriate under some circumstances.
Special processing is performed if fewer than 24 bits are available at the end of the data being encoded. A full encoding quantum is always completed at the end of a body. When fewer than 24 input bits are available in an input group, zero bits are added (on the right) to form an integral number of 6-bit groups. Padding at the end of the data is performed using the «=» character. Since all base64 input is an integral number of octets, only the following cases can arise: (1) the final quantum of encoding input is an integral multiple of 24 bits; here, the final unit of encoded output will be an integral multiple of 4 characters with no «=» padding, (2) the final quantum of encoding input is exactly 8 bits; here, the final unit of encoded output will be two characters followed by two «=» padding characters, or (3) the final quantum of encoding input is exactly 16 bits; here, the final unit of encoded output will be three characters followed by one » =» characters may be taken as evidence that the end of the data has been reached (without truncation in transit). No such assurance is possible, however, when the number of octets transmitted was a multiple of three and no » field_summary»>
Field Summary | |
protected static byte[] | BASE64CARS Table of the sixty-four characters that are used as the Base64 alphabet: [A-Za-z0-9+/] |
protected static java.util.ResourceBundle | labels Locale specific strings displayed to the user. |
protected static byte[] | REVERSEBASE64CHARS Reverse lookup table for the Base64 alphabet. |
static java.lang.String | VERSION Version number of this program |
Method Summary | |
static byte[] | decode (byte[] bytes) Decode Base64 encoded bytes. |
static void | decode (java.io.File fIn) Decode Base64 encoded data from one file to the other. |
static void | decode (java.io.File fIn, boolean throwExceptions) Decode Base64 encoded data from one file to the other. |
static void | decode (java.io.File fIn, java.io.File fOut) Decode Base64 encoded data from one file to the other. |
static void | decode (java.io.File fIn, java.io.File fOut, boolean throwExceptions) Decode Base64 encoded data from one file to the other. |
static void | decode (java.io.InputStream in, java.io.OutputStream out) Decode Base64 encoded data from the InputStream to the OutputStream. |
static void | decode (java.io.InputStream in, java.io.OutputStream out, boolean throwExceptions) Decode Base64 encoded data from the InputStream to the OutputStream. |
static java.lang.String | decode (java.lang.String string) Decode a Base64 encoded String. |
static java.lang.String | decode (java.lang.String string, java.lang.String enc) Decode a Base64 encoded String. |
static byte[] | encode (byte[] bytes) Encode bytes in Base64. |
static void | encode (java.io.File fIn) Encode this file in Base64. |
static void | encode (java.io.File fIn, boolean lineBreaks) Encode this file in Base64. |
static void | encode (java.io.File fIn, java.io.File fOut) Encode this file in Base64. |
static void | encode (java.io.File fIn, java.io.File fOut, boolean lineBreaks) Encode this file in Base64. |
static void | encode (java.io.InputStream in, java.io.OutputStream out) Encode data from the InputStream to the OutputStream in Base64. |
static void | encode (java.io.InputStream in, java.io.OutputStream out, boolean lineBreaks) Encode data from the InputStream to the OutputStream in Base64. |
static java.lang.String | encode (java.lang.String string) Encode a String in Base64. |
static java.lang.String | encode (java.lang.String string, java.lang.String enc) Encode a String in Base64. |
static boolean | isBase64 (byte[] bytes) Determines if the byte array is in base64 format. |
static boolean | isBase64 (java.io.File fIn) Determines if the File is in base64 format. |
static boolean | isBase64 (java.io.InputStream in) Reads data from the stream and determines if it is in base64 format. |
static boolean | isBase64 (java.lang.String string) Determines if the String is in base64 format. |
static boolean | isBase64 (java.lang.String string, java.lang.String enc) Determines if the String is in base64 format. |
Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
BASE64CARS
protected static final byte[] BASE64CARS
REVERSEBASE64CHARS
protected static final byte[] REVERSEBASE64CHARS
Reverse lookup table for the Base64 alphabet. reversebase64Chars[byte] gives n for the nth Base64 character or negative if a character is not a Base64 character.
VERSION
public static final java.lang.String VERSION