Search code examples
javaiobase64

How to read n base64 encoded characters from a file at a time and decode and write to another file?


Currently I have a source file which has base64 encoded data (20 mb in size approx). I want to read from this file, decode the data and write to a .TIF output file. However I don't want to decode all 20MB data at once. I want to read a specific number of characters/bytes from the source file, decode it and write to destination file. I understand that the size of the data I read from the source file has to be in multiples of 4 or else it can't be decoded? Below is my current code where I decode it all at once

public write Output(File file){
BufferedReader br = new BufferedReader (new Filereader(file));
String builder sb = new StringBuilder ();
String line=BR.readLine();
While(line!=null){
....
//Read line by line and append to sb
}
byte[] decoded = Base64.getMimeDecoder().decode(SB.toString());
File outputFile = new File ("output.tif")
OutputStream out = new BufferedOutputStream(new FileOutputStream(outputFile));
out.write(decoded);
out.flush();

}

How can I read specific number of characters from source file and decode and then write to output file so I don't have to load everything in memory?


Solution

  • Here is a simple method to demonstrate doing this, by wrapping the Base64 Decoder around an input stream and reading into an appropriately sized byte array.

    public static void readBase64File(File inputFile, File outputFile, int chunkSize) throws IOException {
        FileInputStream fin = new FileInputStream(inputFile);
        FileOutputStream fout = new FileOutputStream(outputFile);
        InputStream base64Stream = Base64.getMimeDecoder().wrap(fin);
        byte[] chunk = new byte[chunkSize];
        int read;
        while ((read = base64Stream.read(chunk)) != -1) {
            fout.write(chunk, 0, read);
        }
        fin.close();
        fout.close();
    }