0

I'm using Apache Commons Compress to compress files. How do I add a password to the archive so?

public static void main(String args[]) throws FileNotFoundException, IOException {
SevenZOutputFile sevenZOutput = new SevenZOutputFile(new File("outFile.7z"));
File entryFile = new File("D:/image.jpg");
SevenZArchiveEntry entry = sevenZOutput.createArchiveEntry(entryFile, entryFile.getName());
sevenZOutput.putArchiveEntry(entry);
FileInputStream in = new FileInputStream(entryFile);
                int len;
                byte buffer[] = new byte[8192];
                int transferedMegaBytes2=0;
                while ((len = in.read(buffer)) > 0) {
                    sevenZOutput.write(buffer, 0, len);                    
                    transferredBytes += len;
                    int transferedMegaBytes = (int) (transferredBytes / 1048576);                          
                    if(transferedMegaBytes>transferedMegaBytes2){
                    System.out.println("Transferred: " + transferedMegaBytes + " Megabytes.");
                    transferedMegaBytes2=transferedMegaBytes;
                    }
                }
sevenZOutput.closeArchiveEntry();
sevenZOutput.close();    
}
sonik509
  • 119
  • 1
  • 11
  • Rather than trying to protect the archive itself, why not just run out put stream through an encryption stream of some type, so that the content is encrypted and then compressed...? – MadProgrammer Feb 23 '14 at 22:51
  • How did you achieve password protection for 7zip files? – Astha Garg Mar 24 '22 at 07:52

2 Answers2

0

I don't think you can using Commons Compress. From the examples section of the Apache Commons Compress site:

We currently only provide read support for lzma, arj, dump and Z. arj can only read uncompressed archives, 7z can read archives with many compression and encryption algorithms supported by 7z but doesn't support encryption when writing archives.

jpw
  • 44,361
  • 6
  • 66
  • 86
  • 1
    Do you have another library so that I can use? I want to compress with lzma. – sonik509 Feb 23 '14 at 22:49
  • Maybe the 7zip LZMA SDK can do it, I haven't tried it though and the documentation seems a bit lacking. http://www.7-zip.org/sdk.html – jpw Feb 23 '14 at 22:57
0

I am afraid the compression is not supported. You may want to use this JNI wrapper.

If you do that, you'll probably lose the platform independence. (They say it is cross-platform, but I wouldn't bet on it)

Jiri Kremser
  • 12,471
  • 7
  • 45
  • 72