Example of Java's method for automatically compressing and encrypting files

  • 2020-12-19 21:05:44
  • OfStack

An example of Java shows how to automatically compress and encrypt files. To share for your reference, the details are as follows:

Functions: Automatic compression and encryption


/**
*
* @Title: zipFilesAndEncrypt
* @Description:  Compresses the file under the specified path to the specified zip File and encrypt with a specified password , If the password is empty, no encryption protection is performed 
* @param srcFileName  The path to the file to be compressed 
* @param zipFileName zip The file name 
* @param password  Encrypted password 
* @return
* @throws Exception
*/
public void zipFilesAndEncrypt(String srcFileName,String zipFileName,String password) throws Exception{
 ZipOutputStream outputStream=null;
 System.out.println(" Enter the test class ");
 if(StringUtils.isEmpty(srcFileName) || StringUtils.isEmpty(zipFileName)){
  log.error(" The requested compression path or filename is incorrect ");
  return;
 }
 try {
  ZipParameters parameters = new ZipParameters();
  parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
  parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
  if(!StringUtils.isEmpty(password)){
   parameters.setEncryptFiles(true);
   parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);
   parameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);
   parameters.setPassword(password);
  }
  ArrayList<File> filesToAdd = new ArrayList<File>();
  File file=new File(srcFileName);
  File[] files = new File[0];
  if(file.isDirectory())
  {
   files = file.listFiles();
   for(int i=0;i<files.length;i++){
   filesToAdd.add(new File(srcFileName+files[i].getName()));
   System.out.println(" File name: "+files[i].getName());
   }
  }
  else {
   filesToAdd.add(new File(srcFileName+file.getName()));
  }
  ZipFile zipFile = new ZipFile(srcFileName+zipFileName+".zip");
  zipFile.addFiles(filesToAdd, parameters);
 }
 catch (Exception e) {
  System.out.println(" File compression error ");
  log.error(" File compression error ", e);
 throw e;
 }
}

For more information about java algorithm, please refer to Java File and directory Operation Skills Summary, Java Data Structure and Algorithm Tutorial, Java Operation DOM Node Skills Summary and Java Cache Operation Skills Summary.

I hope this article has been helpful in java programming.


Related articles: