Hi,
I have a code that does compression, encryption and checksum on a File Outputstream. Following is the code-
private void start() {
OutputStream os = null;
try {
os = new FileOutputStream("/some/file");
os = wrapAllRequiredTransforms(os);
//Write to os
} finally {
os.close();
}
}
private wrapAllRequiredTransforms(OutputStream os) {
if(checkSumRequired) {
os = wrapOStreamWithCheckSum(os);
}
if(encryptionRequired) {
os = wrapOStreamWithCipher(os);
}
if(compressRequired) {
os = wrapOStreamWithCompress(os);
}
}
private OutputStream wrapOStreamWithCheckSum(OutputStream os) throws Exception {
os = new DigestOutputStream(os, MessageDigest.getInstance("MD5"));
return os;
}
private OutputStream wrapOStreamWithCipher(OutputStream os) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(//SomeKey, encryptionAlgorithm);
Cipher cipher = Cipher.getInstance(encryptionAlgorithm);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
return new CipherOutputStream(os, cipher);
}
private OutputStream wrapOStreamWithCompress(OutputStream os) throws Exception {
return new GZIPOutputStream(os);
}
As you can see here I am wrapping the "os" object for encryption, compression etc., and then re-assigning "os" variable with a different object (created using new) inside each of wrapOStreamWithCheckSum, wrapOStreamWithCipher and wrapOStreamWithCompress methods. I was wondering if this leads to memory leaks by any chance? What would actually happen to the older "os" objects created? To rephrase, there are 4 objects created using "new", but being re-assigned to the same "os" variable. I am finding it hard to understand because the new object creation/functioning itself is dependent on the old object internally.
Thanks,
-Keshav