我有一个对文件输出流进行压缩、加密和校验和的代码。以下是代码-
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);
}
正如您在此处看到的,我正在包装“os”对象以进行加密、压缩等,然后在每个 wrapOStreamWithCheckSum、wrapOStreamWithCipher 和 wrapOStreamWithCompress 方法中重新分配具有不同对象(使用 new 创建)的“os”变量。我想知道这是否会导致内存泄漏?创建的较旧的“os”对象实际上会发生什么?换句话说,使用“new”创建了 4 个对象,但被重新分配给相同的“os”变量。我发现很难理解,因为新对象的创建/运行本身依赖于内部的旧对象。