This article describes the method of Java to automatically compress files and encrypt. Share it for your reference, as follows:
Implementation function: Automatic compression and encryption
/**** @Title: zipFilesAndEncrypt* @Description: Compress the file under the specified path to the specified zip file and encrypt it with the specified password. If the password is empty, no encryption protection is performed* @param srcFileName File path to be compressed* @param zipFileName zipFileName zipfile name* @param password Encryption 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 file name 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 algorithms, readers who are interested in this site can view the topics: "Summary of Java Files and Directory Operation Skills", "Tutorial on Java Data Structures and Algorithms", "Summary of Java Operation DOM Node Skills" and "Summary of Java Cache Operation Skills"
I hope this article will be helpful to everyone's Java programming.