public class Base64Utility {
private static final Logger log = LoggerFactory.getLogger(Base64Utility.class);
private final static char[] ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray();
private static int[] toInt = new int[128];
static {
for (int i = 0; i < ALPHABET.length; i++) {
toInt[ALPHABET[i]] = i;
}
}
/**
* Translates the specified byte array into Base64 string.
*
* @param file the file to encode (not null)
* @return the translated Base64 string (not null)
*/
public static String fileToBase64(File file) throws IOException {
byte[] buf = getBinaryData(file);
int size = buf.length;
char[] ar = new char[((size + 2) / 3) * 4];
int a = 0;
int i = 0;
while (i < size) {
byte b0 = buf[i++];
byte b1 = (i < size) ? buf[i++] : 0;
byte b2 = (i < size) ? buf[i++] : 0;
int mask = 0x3F;
ar[a++] = ALPHABET[(b0 >> 2) & mask];
ar[a++] = ALPHABET[((b0 << 4) | ((b1 & 0xFF) >> 4)) & mask];
ar[a++] = ALPHABET[((b1 << 2) | ((b2 & 0xFF) >> 6)) & mask];
ar[a++] = ALPHABET[b2 & mask];
}
switch (size % 3) {
case 1:
case 2:
ar[--a] = '=';
break;
}
return new String(ar);
}
/**
* Translates the specified Base64 string into a byte array.
*
* @param str the Base64 string (not null)
* @return the byte array (not null)
*/
public static byte[] decode(String str) {
int delta = str.endsWith("==") ? 2 : str.endsWith("=") ? 1 : 0;
byte[] buffer = new byte[str.length() * 3 / 4 - delta];
int mask = 0xFF;
int index = 0;
for (int i = 0; i < str.length(); i += 4) {
int c0 = toInt[str.charAt(i)];
int c1 = toInt[str.charAt(i + 1)];
buffer[index++] = (byte) (((c0 << 2) | (c1 >> 4)) & mask);
if (index >= buffer.length) {
return buffer;
}
int c2 = toInt[str.charAt(i + 2)];
buffer[index++] = (byte) (((c1 << 4) | (c2 >> 2)) & mask);
if (index >= buffer.length) {
return buffer;
}
int c3 = toInt[str.charAt(i + 3)];
buffer[index++] = (byte) (((c2 << 6) | c3) & mask);
}
return buffer;
}
public static byte[] getBinaryData(File file) {
byte[] b = new byte[(int) file.length()];
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
fis.read(b);
} catch (IOException e) {
if (fis != null) {
try {
fis.close();
} catch (IOException e1) {
log.error("can not close FileOutputStream.");
}
}
}
return b;
}
public static File byteArrayToFile(byte[] bytes, String fileFullPath) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(fileFullPath);
fos.write(bytes);
fos.close();
} catch (Exception e) {
if (fos != null) {
try {
fos.close();
} catch (IOException e1) {
log.error("can not close FileOutputStream.");
}
}
}
return new File(fileFullPath);
}
public static File base64ToFile(String str, String fileFullPath) throws IOException {
return byteArrayToFile(decode(str), fileFullPath);
}
}