Java
Chilkat2 Java
Compress and Encrypt a Large File (Low and Constant Memory Footprint)
See more Compression Examples
Demonstrates how to compress and encrypt a large file such that the memory footprint remains low and constant.Note: This example requires Chilkat v9.5.0.99 or greater.
Chilkat Java Downloads
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Compression;
import com.chilkatsoft.chilkat2.Crypt2;
import com.chilkatsoft.chilkat2.JsonObject;
public class ChilkatExample {
public static void main(String[] args) {
// This example assumes the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
Compression compress = new Compression();
compress.setAlgorithm("deflate");
// Set encryption params.
// The possible values are the same as for the corresponding properties in the Chilkat Crypt2 class/object.
// The encoded IV and Key must be specified as hex.
JsonObject json = new JsonObject();
json.updateString("cryptAlgorithm", "aes");
json.updateString("cipherMode", "cbc");
json.updateInt("keyLength", 128);
json.updateInt("paddingScheme", 0);
json.updateString("encodedIV", "000102030405060708090A0B0C0D0E0F");
json.updateString("encodedKey", "000102030405060708090A0B0C0D0E0F");
// Do file-to-file compression+encryption in a single call.
String inPath = "qa_data/largeFile.dat";
String outPath = "c:/temp/qa_output/compressed_encrypted.dat";
try {
compress.compressEncryptFile(json, inPath, outPath);
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
// We can do file-to-file decrypt/decompress like this:
String inPath2 = outPath;
String outPath2 = "c:/temp/qa_output/restored.dat";
try {
compress.decryptDecompressFile(json, inPath2, outPath2);
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
// Note: The above decrypt + decompress is the equivalent of doing the same in these two steps:
Crypt2 crypt = new Crypt2();
crypt.setCryptAlgorithm("aes");
crypt.setCipherMode("cbc");
crypt.setKeyLength(128);
crypt.setPaddingScheme(0);
crypt.setEncodedIV("000102030405060708090A0B0C0D0E0F", "hex");
crypt.setEncodedKey("000102030405060708090A0B0C0D0E0F", "hex");
String decryptedPath = "c:/temp/qa_output/decrypted.dat";
try {
crypt.ckDecryptFile(inPath2, decryptedPath);
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
String outPath3 = "c:/temp/qa_output/restored_in_two_steps.dat";
try {
compress.decompressFile(decryptedPath, outPath3);
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
System.out.println("Success.");
}
}