public static void encode ( InputStream in , OutputStream out , boolean lineBreaks ) throws IOException { // Base64 encoding converts three bytes of input to // four bytes of output int [ ] inBuffer = new int [ 3 ] ; int lineCount = 0 ; boolean done = false ; while ( ! done && ( inBuffer [ 0 ] = in . read ( ) ) != END_OF_INPUT ) { // Fill the buffer inBuffer [ 1 ] = in . read ( ) ; inBuffer [ 2 ] = in . read ( ) ; // Calculate the out Buffer // The first byte of our in buffer will always be valid // but we must check to make sure the other two bytes // are not END_OF_INPUT before using them. // The basic idea is that the three bytes get split into // four bytes along these lines: // [AAAAAABB] [BBBBCCCC] [CCDDDDDD] // [xxAAAAAA] [xxBBBBBB] [xxCCCCCC] [xxDDDDDD] // bytes are considered to be zero when absent. // the four bytes are then mapped to common ASCII symbols // A's: first six bits of first byte out . write ( base64Chars [ inBuffer [ 0 ] >> 2 ] ) ; if ( inBuffer [ 1 ] != END_OF_INPUT ) { // B's: last two bits of first byte, first four bits of second byte out . write ( base64Chars [ ( ( inBuffer [ 0 ] << 4 ) & 0x30 ) | ( inBuffer [ 1 ] >> 4 ) ] ) ; if ( inBuffer [ 2 ] != END_OF_INPUT ) { // C's: last four bits of second byte, first two bits of third byte out . write ( base64Chars [ ( ( inBuffer [ 1 ] << 2 ) & 0x3c ) | ( inBuffer [ 2 ] >> 6 ) ] ) ; // D's: last six bits of third byte out . write ( base64Chars [ inBuffer [ 2 ] & 0x3F ] ) ; } else { // C's: last four bits of second byte out . write ( base64Chars [ ( ( inBuffer [ 1 ] << 2 ) & 0x3c ) ] ) ; // an equals sign for a character that is not a Base64 character out . write ( ' ' ) ; done = true ; } } else { // B's: last two bits of first byte out . write ( base64Chars [ ( ( inBuffer [ 0 ] << 4 ) & 0x30 ) ] ) ; // an equal signs for characters that is not a Base64 characters out . write ( ' ' ) ; out . write ( ' ' ) ; done = true ; } lineCount += 4 ; if ( lineBreaks && lineCount >= 76 ) { out . write ( ' ' ) ; lineCount = 0 ; } } if ( lineBreaks && lineCount >= 1 ) { out . write ( ' ' ) ; lineCount = 0 ; } out . flush ( ) ; }
Encode data from the InputStream to the OutputStream in Base64 .