Next:
MIME Content Types
Up:
Lecture 5
Previous:
Base64 Decoding
Use of Base64 Encoding
Base64 class can be exercised by code such as
import java.io.*;
public class Code {
public static void main(String[] args) throws IOException {
Base64.init();
if ( args[0].equals("-d") ) {
BufferedReader br = new BufferedReader(
new InputStreamReader(new FileInputStream(args[1])));
String s, t = "";
while ( (s = br.readLine()) != null ) t += s;
System.out.write(Base64.decode(t.getBytes()));
} else {
int len = (int)(new File(args[0])).length();
FileInputStream fis = new FileInputStream(args[0]);
byte[] buf = new byte[len];
int i = 0, n;
do {
n = fis.read(buf, i, len - i);
if ( n != -1 ) i += n;
} while ( i < len && n != -1 );
byte[] b = Base64.encode(buf);
for (i=0; i<b.length; i++) {
if ( i != 0 && i % 72 == 0 )
System.out.write(10);
System.out.write(b[i]);
}
}
System.out.flush();
}
}
Code.java encodes report.doc file
C:\> java Code report.doc > report.b64
It outputs base64 code chopped up into lines of 72 letters.
Code.java decodes report.b64 file
C:\> java Code -d report.b64 > report.doc
It reads in lines of base64 code and reconstitutes the original file.