Base64 encodes a file in chunks

I want to split the file into several pieces (in this case, try length 300) and base64 encode it, since loading the entire file into memory gives a negative array exception when encoding base64. I tried using the following code:

int offset = 0;
bis = new BufferedInputStream(new FileInputStream(f));
while(offset + 300 <= f.length()){
    byte[] temp = new byte[300];
    bis.skip(offset);
    bis.read(temp, 0, 300);
    offset += 300;
    System.out.println(Base64.encode(temp));
}
if(offset < f.length()){
    byte[] temp = new byte[(int) f.length() - offset];
    bis.skip(offset);
    bis.read(temp, 0, temp.length);
    System.out.println(Base64.encode(temp));
}

At first it works, but at some point it switches to a simple "AAAAAAAAA" and fills it with the entire console, and the new file gets corrupted during decoding. What can cause this error?

+4
source share
1 answer

skip()"Skips and deletes n bytes of data from the input stream", and read()returns "the number of bytes read."

, , , , ,... EOF, read() -1, temp, 0, A.

:

try (InputStream in = new BufferedInputStream(new FileInputStream(f))) {
    int len;
    byte[] temp = new byte[300];
    while ((len = in.read(temp)) > 0)
        System.out.println(Base64.encode(temp, 0, len));
}

, , , .

Base64.encode , :

try (InputStream in = new BufferedInputStream(new FileInputStream(f))) {
    int len;
    byte[] temp = new byte[300];
    while ((len = in.read(temp)) > 0) {
        byte[] data;
        if (len == temp.length)
            data = temp;
        else {
            data = new byte[len];
            System.arraycopy(temp, 0, data, 0, len);
        }
        System.out.println(Base64.encode(data));
    }
}
+1

All Articles