So today I found myself needing to test base64 encoding in Java so I could compare the same results on the RPG end. Being that it took me longer than necessary to put the code together I thought I would post it online. Note this code is compiled using JDK 1.5 (aka 5.0).
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.xerces.impl.dv.util.Base64;
public class Base64CopyToFrom {
public static void main(String args[]) {
base64EncodeFile("c:/temp/newimage.tif", "c:/temp/newimage_base64encoded.txt");
base64DecodeFile("c:/temp/newimage_base64encoded.txt", "c:/temp/newimage_1.tif");
}
static void base64EncodeFile(String fileToEncode, String resultingFile){
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream(fileToEncode);
os = new FileOutputStream(resultingFile);
int bytesRead = 0;
int chunkSize = 10000000;
byte[] chunk = new byte[chunkSize];
while ((bytesRead = is.read(chunk)) > 0) {
byte[] ba = new byte[bytesRead];
for(int i=0; i
ba[i] = chunk[i];
}
String encStr = Base64.encode(ba);
os.write(encStr.getBytes(), 0, encStr.length());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
static void base64DecodeFile(String fileToDecode, String resultingFile){
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream(fileToDecode);
os = new FileOutputStream(resultingFile);
int bytesRead = 0;
int chunkSize = 10000000;
byte[] chunk = new byte[chunkSize];
while ((bytesRead = is.read(chunk)) > 0) {
byte[] ba = new byte[bytesRead];
for(int i=0; i
ba[i] = chunk[i];
}
ba = Base64.decode(new String(ba));
os.write(ba, 0, ba.length);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}