Javaはファイルの圧縮と暗号化を実現します。

2992 ワード

最近の仕事のために、zip 4 jに基づいて、ファイルの圧縮と暗号化のための機能が実現されました。コードは以下の通りです。
/**
* 
* @Title: zipFilesAndEncrypt
* @Description:               zip  ,              ,        
* @param srcFileName        
* @param zipFileName zip   
* @param password      
* @return
* @throws Exception 
*/
public static void zipFilesAndEncrypt(String srcFileName,String zipFileName,String password) throws Exception{
ZipOutputStream outputStream = null;
InputStream inputStream = null;
if(StringUtils.isEmpty(srcFileName) || StringUtils.isEmpty(zipFileName)){
throw new NullArgumentException("            ");
}
try {
File srcFile = new File(srcFileName);   
File[] files = new File[0];
if (srcFile.isDirectory()) {
files = srcFile.listFiles();
} else {
files = new File[1];
files[0] = srcFile;
}
outputStream = new ZipOutputStream(new FileOutputStream(new File(zipFileName)));
ZipParameters parameters = new ZipParameters();
parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
if(!StringUtils.isEmpty(password)){
parameters.setEncryptFiles(true);
//Zip4j supports AES or Standard Zip Encryption (also called ZipCrypto)
//If you choose to use Standard Zip Encryption, please have a look at example
//as some additional steps need to be done while using ZipOutputStreams with
//Standard Zip Encryption
parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);
parameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);
parameters.setPassword(password);
}

//Now we loop through each file and read this file with an inputstream
//and write it to the ZipOutputStream.
int fileNums = files.length;
for (int i = 0; i < fileNums; i++) {
File file = (File)files[i];

//This will initiate ZipOutputStream to include the file
//with the input parameters
outputStream.putNextEntry(file,parameters);

//If this file is a directory, then no further processing is required
//and we close the entry (Please note that we do not close the outputstream yet)
if (file.isDirectory()) {
outputStream.closeEntry();
continue;
}

inputStream = new FileInputStream(file);
byte[] readBuff = new byte[4096];
int readLen = -1;
//Read the file content and write it to the OutputStream
while ((readLen = inputStream.read(readBuff)) != -1) {
outputStream.write(readBuff, 0, readLen);
}
//Once the content of the file is copied, this entry to the zip file
//needs to be closed. ZipOutputStream updates necessary header information
//for this file in this step
outputStream.closeEntry();
inputStream.close();
}
//ZipOutputStream now writes zip header information to the zip file
outputStream.finish();
} catch (Exception e) {
log.error("      ", e);
throw e;
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
log.error("        ", e);
throw e;
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
log.error("      ", e);
throw e;
}
}
}
}