Base64 Encoding


Having seen how character encodings can have a major impact on our data, let's look at how the Base64 Codec can be used to convert binary data to a format easily represented by ASCII characters. Many systems understand and can easily transmit binary data when encoding using Base64in particular, Base64 encoding is commonly found when sending binary files as email attachments.

Listing 12-4 shows how a binary file (in this case, a small GIF) can be loaded and converted to 7-bit ASCII characters. Generally speaking, 7-bit ASCII characters are safe for transmission across a variety of systemseven copying and pasting from one application to another on a wide variety of systems.

Listing 12-4. Base64 File Encoding Source
 public static void fileEncodingDemo() {     printHeader("Base64 File Encoding Test");     java.io.File myFile = new java.io.File("demo.gif");     try     {         if (myFile.exists());         {             FileInputStream myFileContents =                 new FileInputStream(myFile);             byte[] fileContents =                 new byte[(int)myFile.length()];             myFileContents.read(fileContents);             String myGIF = new String(fileContents);             System.out.println(                 "Notice the strange, non-ASCII characters...");             System.out.println(myGIF.substring(0, 79));             System.out.println();             byte[] result;             result = Base64.encodeBase64Chunked(fileContents);             System.out.println(                 "Note all ASCII characters, and that the data ");             System.out.println(                 "is automatically formatted to 79 characters");             System.out.println(new String(result));         }     } catch (Exception e)     {         e.printStackTrace();     } } 

When run, the application produces output as shown in Listing 12-5 (for a very small test GIF). You'll notice that instead of using the simple encode() method, we took advantage of a encodeBase64Chunked() utility method to retrieve data already broken into 76 character wide columnseasily used on even legacy 80 character column terminal displays.

Listing 12-5. Base64 File Encoding Results
 ================================ Base64 File Encoding Test ================================ Notice the strange, non-ASCII characters... GIF89a<<unprintable characters, will vary on your terminal>> Note all ASCII characters, and that the data is automatically formatted to 76 characters R0lGODlhIAAgAIAAAP///wAAACwAAAAAIAAgAAACUkyAqcuNdpycAEaKk72Zbt45HxguI1k+Z8qc Bqu4L1zJaGbPaa6HfI/73UTCYatojCGTqiVmCfFAgaYpVWO91rIobrTqBYW/zTF2PENbtuq2pQAA Ow== 



    Apache Jakarta Commons(c) Reusable Java Components
    Real World Web Services
    ISBN: N/A
    EAN: 2147483647
    Year: 2006
    Pages: 137
    Authors: Will Iverson

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net