Base64 encodes a file and compresses it

My goal is to encode a file and pin it to a folder in java. I have to use the Apache Commons-codec library. I can encode and zip it, and it works fine, but when I decode it back to its original form, it looks like the file was not fully encoded. Some parts seem to be missing. Can someone tell me why this is happening?

I also attach part of my code for your link so you can direct me accordingly.

private void zip() {
    int BUFFER_SIZE = 4096;
    byte[] buffer = new byte[BUFFER_SIZE];

    try {
        // Create the ZIP file
        String outFilename = "H:\\OUTPUT.zip";
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
                outFilename));

        // Compress the files
        for (int i : list.getSelectedIndices()) {
            System.out.println(vector.elementAt(i));
            FileInputStream in = new FileInputStream(vector.elementAt(i));
            File f = vector.elementAt(i);

            // Add ZIP entry to output stream.
            out.putNextEntry(new ZipEntry(f.getName()));

            // Transfer bytes from the file to the ZIP file
            int len;

            while ((len = in.read(buffer)) > 0) {
                buffer = org.apache.commons.codec.binary.Base64
                        .encodeBase64(buffer);
                out.write(buffer, 0, len);

            }

            // Complete the entry
            out.closeEntry();
            in.close();

        }

        // Complete the ZIP file
        out.close();
    } catch (IOException e) {
        System.out.println("caught exception");
        e.printStackTrace();
    }
}
+5
source share
3 answers

BASE64 encoded data is usually longer than the source, however you use the length of the source data to write the encoded data to the output stream.

len.

- buffer , . .

 while ((len = in.read(buffer)) > 0)  {                         
     byte [] enc = Base64.encodeBase64(Arrays.copyOf(buffer, len));
     out.write(enc, 0, enc.length);
 }

UPDATE: Arrays.copyOf(...), .

+3

, base64 ( apache-commons). , , , , in.read(..).

:

0

, len . base64 , , len , len . beans, .

, base64 LEN , 0s .

, base64 ( []), , , base64 . , .

The smaller problem is that when reading in your loop, you should probably check "> -1" and not "> 0", but that doesn't matter in his case.

0
source

All Articles