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).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 | 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(); } } } } |