如何一次从一个文件中读取n个base64编码的字符并解码写入另一个文件?

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

目前我有一个包含 base64 编码数据的源文件(大小约为 20 MB)。我想从这个文件中读取数据,解码数据并写入 .TIF 输出文件。但是我不想一次解码所有 20MB 数据。我想从源文件中读取特定数量的 characters/bytes ,对其进行解码并写入目标文件。我明白我从源文件中读取的数据大小必须是4的倍数,否则无法解码? 下面是我当前的代码,我一次解码它

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();

}

如何从源文件中读取特定数量的字符并解码,然后写入输出文件,这样我就不必将所有内容都加载到内存中?

这里有一个简单的方法来演示如何执行此操作,方法是将 Base64 Decoder 环绕输入流并读入适当大小的字节数组。

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();
}