Encode a binary file with Base64 encoder in Java 

Joined:
04/09/2007
Posts:
773

June 03, 2010 22:43:43    Last update: June 20, 2010 14:13:05
Using the Sun BASE64Encoder:
import java.io.*;
import sun.misc.BASE64Encoder;

public class EncodeFileWithBase64 {
    public static void main(String[] args) throws Exception {
	if (args.length < 2) {
	    System.out.println("Usage: java EncodeFileWithBASE64 <inputFile> <outputFile>");
	    return;
	}

	String inputFile = args[0];
	String outputFile = args[1];

	BASE64Encoder encoder = new BASE64Encoder();
	encoder.encode(
	    new FileInputStream(inputFile),
	    new FileOutputStream(outputFile)
	);
    }
}


However, the Sun encoder is awfully slow.
The Apache encoder is a lot faster. Here's the code with Apache encoder:
import java.io.*;
import org.apache.commons.codec.binary.Base64OutputStream;

public class EncodeBase64WithApache {
    public static void main(String[] args) throws Exception {
	if (args.length < 2) {
	    System.out.println("Usage: java EncodeBase64WithApache <inputFile> <outputFile>");
	    return;
	}

	int BUFFER_SIZE = 4096;
	byte[] buffer = new byte[BUFFER_SIZE];
	InputStream input = new FileInputStream(args[0]);
	OutputStream output = new Base64OutputStream(new FileOutputStream(args[1]));
	int n = input.read(buffer, 0, BUFFER_SIZE);
	while (n >= 0) {
	    output.write(buffer, 0, n);
	    n = input.read(buffer, 0, BUFFER_SIZE);
	}
	input.close();
	output.close();
    }
}


Performance comparisons between Apache and Sun:
C:\>bash
bash-3.2$ time java EncodeFileWithBase64 test.zip test_b64sun.txt

real    0m6.343s
user    0m0.031s
sys     0m0.046s

bash-3.2$ time java EncodeBase64WithApache test.zip test_b64apache.txt

real    0m0.328s
user    0m0.015s
sys     0m0.062s
bash-3.2$
Share |
| Comment  | Tags