Java Code Examples for net.lingala.zip4j.core.ZipFile

The following examples show how to use net.lingala.zip4j.core.ZipFile. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: AndroidZip   Source File: ZipManager.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 压缩多个文件
 *
 * @param list                被压缩的文件集合
 * @param destinationFilePath 压缩后生成的文件路径
 * @param password            压缩 密码
 * @param callback            回调
 */
public static void zip(ArrayList<File> list, String destinationFilePath, String password, final IZipCallback callback) {
    if (list == null || list.size() == 0 || !Zip4jUtil.isStringNotNullAndNotEmpty(destinationFilePath)) {
        if (callback != null) callback.onFinish(false);
        return;
    }
    ZipLog.debug("zip: list=" + list.toString() + " , destinationFilePath=" + destinationFilePath + " , password=" + password);
    try {
        ZipParameters parameters = new ZipParameters();
        parameters.setCompressionMethod(8);
        parameters.setCompressionLevel(5);
        if (password.length() > 0) {
            parameters.setEncryptFiles(true);
            parameters.setEncryptionMethod(99);
            parameters.setAesKeyStrength(3);
            parameters.setPassword(password);
        }
        ZipFile zipFile = new ZipFile(destinationFilePath);
        zipFile.setRunInThread(true);
        zipFile.addFiles(list, parameters);
        timerMsg(callback, zipFile);
    } catch (Exception e) {
        if (callback != null) callback.onFinish(false);
        ZipLog.debug("zip: Exception=" + e.getMessage());
    }
}
 
Example 2
Source Project: AndroidZip   Source File: ZipManager.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 解压
 *
 * @param targetZipFilePath     待解压目标文件地址
 * @param destinationFolderPath 解压后文件夹地址
 * @param password              解压密码
 * @param callback              回调
 */
public static void unzip(String targetZipFilePath, String destinationFolderPath, String password, final IZipCallback callback) {
    if (!Zip4jUtil.isStringNotNullAndNotEmpty(targetZipFilePath) || !Zip4jUtil.isStringNotNullAndNotEmpty(destinationFolderPath)) {
        if (callback != null) callback.onFinish(false);
        return;
    }
    ZipLog.debug("unzip: targetZipFilePath=" + targetZipFilePath + " , destinationFolderPath=" + destinationFolderPath + " , password=" + password);
    try {
        ZipFile zipFile = new ZipFile(targetZipFilePath);
        if (zipFile.isEncrypted() && Zip4jUtil.isStringNotNullAndNotEmpty(password)) {
            zipFile.setPassword(password);
        }
        zipFile.setRunInThread(true);
        zipFile.extractAll(destinationFolderPath);
        timerMsg(callback, zipFile);
    } catch (Exception e) {
        if (callback != null) callback.onFinish(false);
        ZipLog.debug("unzip: Exception=" + e.getMessage());
    }
}
 
Example 3
Source Project: AndroidZip   Source File: ZipManager.java    License: Apache License 2.0 6 votes vote down vote up
private static void timerMsg(final IZipCallback callback, ZipFile zipFile) {
    if (callback == null) return;
    mUIHandler.obtainMessage(WHAT_START, callback).sendToTarget();
    final ProgressMonitor progressMonitor = zipFile.getProgressMonitor();
    final Timer           timer           = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            mUIHandler.obtainMessage(WHAT_PROGRESS, progressMonitor.getPercentDone(), 0, callback).sendToTarget();
            if (progressMonitor.getResult() == ProgressMonitor.RESULT_SUCCESS) {
                mUIHandler.obtainMessage(WHAT_FINISH, callback).sendToTarget();
                this.cancel();
                timer.purge();
            }
        }
    }, 0, 300);
}
 
Example 4
public List<String> listEntries(File zipsource) {
	List<String> files = new ArrayList<String>();
	try {
		ZipFile zipFile = new ZipFile(zipsource);
		setCharset(zipFile);

		@SuppressWarnings("unchecked")
		List<FileHeader> fileHeaders = zipFile.getFileHeaders();
		for (FileHeader fileHeader : fileHeaders) {
			files.add(fileHeader.getFileName());
		}
	} catch (Throwable e) {
		logError(e.getMessage());
	}
	return files;
}
 
Example 5
public static void addEntry(File zip, String entry, InputStream content) {
	try {
		// read war.zip and write to
		ZipFile zipFile = new ZipFile(zip);
		ZipParameters parameters = new ZipParameters();
		parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
		// this would be the name of the file for this entry in the zip file
		parameters.setFileNameInZip(entry);

		// we set this flag to true. If this flag is true, Zip4j identifies
		// that
		// the data will not be from a file but directly from a stream
		parameters.setSourceExternalStream(true);

		// Creates a new entry in the zip file and adds the content to the
		// zip
		// file
		zipFile.addStream(content, parameters);
	} catch (Exception e) {
		logError(e.getMessage());
	}
}
 
Example 6
Source Project: ResourcePackConverter   Source File: ZipPack.java    License: MIT License 6 votes vote down vote up
@Override
public void setup() throws IOException {
    if (pack.getWorkingPath().toFile().exists()) {
        System.out.println("  Deleting existing conversion");
        Util.deleteDirectoryAndContents(pack.getWorkingPath());
    }

    Path convertedZipPath = getConvertedZipPath();
    if (convertedZipPath.toFile().exists()) {
        System.out.println("  Deleting existing conversion zip");
        convertedZipPath.toFile().delete();
    }

    pack.getWorkingPath().toFile().mkdir();

    try {
        ZipFile zipFile = new ZipFile(pack.getOriginalPath().toFile());
        zipFile.extractAll(pack.getWorkingPath().toString());
    } catch (ZipException e) {
        Util.propagate(e);
    }
}
 
Example 7
Source Project: butterfly   Source File: CompressionHandler.java    License: MIT License 6 votes vote down vote up
void compress(TransformationResult transformationResult) {
    File inputFile = transformationResult.getTransformedApplicationDir().getAbsoluteFile();
    File compressedFile = new File(transformationResult.getTransformedApplicationDir().getAbsolutePath() + ".zip");

    logger.info("Compressing transformed application");

    try {
        ZipFile zipFile = new ZipFile(compressedFile);
        ZipParameters parameters = new ZipParameters();

        parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
        parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);

        zipFile.addFolder(inputFile, parameters);
        FileUtils.deleteDirectory(transformationResult.getTransformedApplicationDir());

        logger.info("Transformed application has been compressed to {}", compressedFile.getAbsoluteFile());
    } catch (Exception e) {
        logger.error("An exception happened when compressing transformed application", e);
    }
}
 
Example 8
Source Project: Mzip-Android   Source File: ZipArchive.java    License: Apache License 2.0 6 votes vote down vote up
public static void zip(String targetPath, String destinationFilePath, String password) {
    try {
        ZipParameters parameters = new ZipParameters();
        parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
        parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);

        if (password.length() > 0) {
            parameters.setEncryptFiles(true);
            parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);
            parameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);
            parameters.setPassword(password);
        }

        ZipFile zipFile = new ZipFile(destinationFilePath);

        File targetFile = new File(targetPath);
        if (targetFile.isFile()) {
            zipFile.addFile(targetFile, parameters);
        } else if (targetFile.isDirectory()) {
            zipFile.addFolder(targetFile, parameters);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 9
Source Project: MonitorClient   Source File: ZipUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 添加文件夹到zip中
 * @data 2017年4月18日
 * @param inPath
 * @param storagePath
 * @param outPath
 * @param password
 * @return
 */
public static boolean addFoldInZip(String inPath,String storagePath,String outPath,String password) {
	try {
		ZipFile zipFile = new ZipFile(outPath);  
		ZipParameters parameters = new ZipParameters();       
		parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);         
		parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
		parameters.setRootFolderInZip(storagePath);  ;  
		if(password!=null&&!password.equals("")){
			parameters.setEncryptFiles(true);  
			parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);  
			parameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);  
			parameters.setPassword(password);  
		}
		zipFile.addFolder(inPath, parameters);  		
		return true;
	} catch (ZipException e) {
		e.printStackTrace();
		return false;
	}
}
 
Example 10
Source Project: MonitorClient   Source File: ZipUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 添加文件到zip中指定的文件夹中
 * @param inPath
 * @param storagePath
 * @param outPath
 * @param password
 * @return
 */
public static boolean addFileInZip(String inPath,String storagePath,String outPath,String password) {
	try {

		ZipFile zipFile = new ZipFile(outPath);
		File inFile = new File(inPath);
		ZipParameters parameters = new ZipParameters();
		parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE); // set compression method to deflate compression
		parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL); 
		parameters.setRootFolderInZip(storagePath);  
		if(password!=null&&!password.equals("")){
			parameters.setEncryptFiles(true);  
			parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);  
			parameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);  
			parameters.setPassword(password); 
		}
		zipFile.addFile(inFile, parameters);
		return true;
	} catch (ZipException e) {
		e.printStackTrace();
		return false;
	}
}
 
Example 11
Source Project: MonitorClient   Source File: ZipUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 添加多个文件到zip中指定的文件夹中
 * @param inPath
 * @param storagePath
 * @param outPath
 * @param password
 * @return
 */
public static boolean addFilesInZip(ArrayList<File> inFiles,String storagePath,String outPath,String password) {
	try {
		ArrayList filesToAdd = new ArrayList();  
		ZipFile zipFile = new ZipFile(outPath);
		ZipParameters parameters = new ZipParameters();
		parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE); // set compression method to deflate compression
		parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL); 
		parameters.setRootFolderInZip(storagePath);  
		if(password!=null&&!password.equals("")){
			parameters.setEncryptFiles(true);  
			parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);  
			parameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);  
			parameters.setPassword(password); 
		}
		zipFile.addFiles(inFiles, parameters);
		return true;
	} catch (ZipException e) {
		e.printStackTrace();
		return false;
	}
}
 
Example 12
Source Project: MonitorClient   Source File: ZipUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 查看压缩包的文件列表
 * @param inPath
 * @param password
 * @return
 */
public static boolean getNameFromZip(String inPath,String password) {
	try {
		ZipFile zipFile = new ZipFile(inPath);
		if (zipFile.isEncrypted()) {  
			zipFile.setPassword(password);  
		}  
		List fileHeaderList = zipFile.getFileHeaders();  
		  
		for (int i = 0; i < fileHeaderList.size(); i++) {  
		    FileHeader fileHeader = (FileHeader)fileHeaderList.get(i); 
		    System.out.println("Name: " + fileHeader.getFileName());  
		    System.out.println("Compressed Size: " + fileHeader.getCompressedSize());  
		    System.out.println("Uncompressed Size: " + fileHeader.getUncompressedSize());  
		    System.out.println("CRC: " + fileHeader.getCrc32());  
		    System.out.println("************************************************************");  
		}  
		return true;
	} catch (ZipException e) {
		e.printStackTrace();
		return false;
	}
}
 
Example 13
Source Project: at.info-knowledge-base   Source File: FilesUtils.java    License: MIT License 6 votes vote down vote up
public static Status unZipItems(final String filePath, final String outputFolder) {
    Status response;

    if (getExtension(filePath).equals("zip")) {
        try {
            new ZipFile(filePath).extractAll(outputFolder);
            IO_LOGGER.info("All files have been successfully extracted!");
            response = Status.OK;
        } catch (ZipException e) {
            IO_LOGGER.severe("Unable extract files from " + filePath + ": " + e.getMessage());
            response = Status.INTERNAL_SERVER_ERROR;
        }
    } else {
        response = Status.NOT_FOUND;
    }

    return response;
}
 
Example 14
Source Project: ApkToolPlus   Source File: ZipUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 解压文件到指定目录
 *
 * @param zipFile      压缩文件
 * @param outDir       输出路径
 * @param isClean      是否清理目录
 * @return
 */
public static boolean unzip(File zipFile, File outDir, boolean isClean){
    try {
        if(!FileHelper.exists(zipFile)){
            return false;
        }
        ZipFile zip = new ZipFile(zipFile);
        if(isClean && outDir.exists()){
            FileHelper.delete(outDir);
        }
        zip.setRunInThread(false);
        zip.extractAll(outDir.getPath());
        return true;
    } catch (ZipException e) {
        e.printStackTrace();
    }
    return false;
}
 
Example 15
Source Project: ApkToolPlus   Source File: ZipUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 解压文件,注意该法方法并不是异步的
 *
 * @param zipFile      压缩文件
 * @param filter
 * @return
 */
public static void list(File zipFile, FileFilter filter){
    try {
        if(!FileHelper.exists(zipFile)){
            return;
        }
        ZipFile zip = new ZipFile(zipFile);
        zip.setRunInThread(false);

        // Get the list of file headers from the zip file
        List fileHeaderList = zip.getFileHeaders();

        // Loop through the file headers
        for (int i = 0; i < fileHeaderList.size(); i++) {
            // Extract the file to the specified destination
            filter.handle(zip, (FileHeader) fileHeaderList.get(i));
        }
    } catch (ZipException e) {
        e.printStackTrace();
    }
}
 
Example 16
Source Project: ApkToolPlus   Source File: MultDexSupport.java    License: Apache License 2.0 6 votes vote down vote up
protected List<File> unzipDexList(File apk, File tempDir){
    List<FileHeader> dexFileHeaders = MultDexSupport.getDexFileHeaders(apk);
    if(dexFileHeaders.isEmpty()){
        return new ArrayList<>(0);
    }
    // 解压dex文件
    tempDir.mkdirs();
    List<File> dexFileList = new ArrayList<>(dexFileHeaders.size());
    try {
        for(FileHeader dexFileHeader : dexFileHeaders){
            ZipFile zipFile = new ZipFile(apk);
            boolean unzip = ZipUtils.unzip(zipFile, dexFileHeader, tempDir);
            if(unzip){
                dexFileList.add(new File(tempDir,dexFileHeader.getFileName()));
            }
        }
        return dexFileList;
    } catch (ZipException e) {
        e.printStackTrace();
    }
    return new ArrayList<>(0);
}
 
Example 17
private void generateZipFile() {
	try {
		File outputFile = new File(this.workFolder.getName() + ".zip");
		if (outputFile.exists()) {
			Logger.info(outputFile.getAbsolutePath() + " already exists. Deleting.");
			outputFile.delete();
		}
		ZipFile output = new net.lingala.zip4j.core.ZipFile(outputFile);
		Logger.info("Generating " + output.getFile().getAbsolutePath());

		ZipParameters params = new ZipParameters();
		params.setIncludeRootFolder(false);
		params.setRootFolderInZip("");
		output.addFolder(this.workFolder.getAbsolutePath() + File.separator + "apktool", params);
		params.setRootFolderInZip("classes");
		output.addFolder(this.workFolder.getAbsolutePath() + File.separator + "classes", params);
	} catch (Throwable t) {
		Logger.error("Unable to generate final zip file.", t);
	}
}
 
Example 18
Source Project: thorntail   Source File: BuildTool.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private void expandArtifact(File artifactFile) throws IOException {
    try {
        ZipFile zipFile = new ZipFile(artifactFile);
        for (FileHeader each : (List<FileHeader>) zipFile.getFileHeaders()) {
            String fileName = each.getFileName();
            if (fileName.startsWith("META-INF") && !fileName.startsWith("META-INF/versions")) {
                continue;
            }
            if (each.isDirectory()) {
                continue;
            }
            this.archive.add(new ZipFileHeaderAsset(zipFile, each), fileName);
        }
    } catch (ZipException e) {
        throw new IOException(e);
    }
}
 
Example 19
Source Project: maven-framework-project   Source File: Zip4j.java    License: MIT License 6 votes vote down vote up
/**
 * 示例7 解压压缩文件
 */
@Test
public void example7(){
	
	example4();
	
	try {
           ZipFile zipFile = new ZipFile("src/main/resources/AddFilesWithAESZipEncryption.zip");
           if (zipFile.isEncrypted()) {
               // if yes, then set the password for the zip file
               zipFile.setPassword("123456");
               zipFile.extractAll("src/main/resources/zipfile");
           }
       } catch (ZipException e) {
           e.printStackTrace();
       }
}
 
Example 20
private void generateZipFile() {
	try {
		File outputFile = new File(this.workFolder.getName() + ".zip");
		if (outputFile.exists()) {
			Logger.info(outputFile.getAbsolutePath() + " already exists. Deleting.");
			outputFile.delete();
		}
		ZipFile output = new net.lingala.zip4j.core.ZipFile(outputFile);
		Logger.info("Generating " + output.getFile().getAbsolutePath());

		ZipParameters params = new ZipParameters();
		params.setIncludeRootFolder(false);
		params.setRootFolderInZip("");
		output.addFolder(this.workFolder.getAbsolutePath() + File.separator + "apktool", params);
		params.setRootFolderInZip("classes");
		output.addFolder(this.workFolder.getAbsolutePath() + File.separator + "classes", params);
	} catch (Throwable t) {
		Logger.error("Unable to generate final zip file.", t);
	}
}
 
Example 21
Source Project: proarc   Source File: DesaElementVisitor.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Archives the list of files to a zip archive
 *
 * @param zipFileName
 * @param fileList
 * @param desaElement
 * @throws MetsExportException
 */
private void zip(String zipFileName, ArrayList<File> fileList, IDesaElement desaElement) throws MetsExportException {
    try {
        File file = new File(zipFileName);
        if (file.exists()) {
            file.delete();
            file = null;
            LOG.log(Level.FINE, "File:" + zipFileName + " exists, so it was deleted");
        }
        ZipFile zipFile = new ZipFile(zipFileName);
        ZipParameters zip4jZipParameters = new ZipParameters();
        zip4jZipParameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
        zip4jZipParameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
        zipFile.addFiles(fileList, zip4jZipParameters);
        LOG.log(Level.FINE, "Zip archive created:" + zipFileName + " for " + desaElement.getElementType());
    } catch (ZipException e) {
        throw new MetsExportException(desaElement.getOriginalPid(), "Unable to create a zip file:" + zipFileName, false, e);
    }

}
 
Example 22
Source Project: KAM   Source File: RestoreAppsTasker.java    License: GNU General Public License v3.0 6 votes vote down vote up
private void withData() throws Exception {
    FileUtil fileUtil = new FileUtil();
    File dataFile = new File(fileUtil.getBaseFolderName() + "data.zip");
    dataZip = new ZipFile(dataFile);
    if (dataZip.getFileHeaders() != null) {
        List fileHeaderList = dataZip.getFileHeaders();
        ProgressModel progressModel = new ProgressModel();
        progressModel.setMax(fileHeaderList.size());
        publishProgress(progressModel);
        List<FileHeader> headers = dataZip.getFileHeaders();
        for (FileHeader header : headers) {
            dataZip.extractFile(header, fileUtil.getBaseFolderName());
            copyFileToData(fileUtil.getBaseFolderName(), header.getFileName());
        }
    }
    FileUtils.forceDelete(dataFile);
}
 
Example 23
Source Project: maven-framework-project   Source File: Zip4j.java    License: MIT License 6 votes vote down vote up
/**
 * 示例1 创建压缩包添加文件到压缩包中(未设置加密)
 */
@Test
public void example1(){
	try {
           
           ZipFile zipFile = new ZipFile("src/main/resources/AddFilesDeflateComp.zip");
            
           ArrayList<File> filesToAdd = new ArrayList<File>();
           filesToAdd.add(new File("src/main/resources/sample.txt"));
           filesToAdd.add(new File("src/main/resources/zip4j.txt"));
           filesToAdd.add(new File("src/main/resources/zip4j-1.3.2.jar"));
            
           ZipParameters parameters = new ZipParameters();
           parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE); // set compression method to deflate compression
           parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL); 
           zipFile.addFiles(filesToAdd, parameters);
           
           CompressUtil.printZipInfo("src/main/resources/AddFilesDeflateComp.zip");
           
           
       } catch (ZipException e) {
           e.printStackTrace();
       }
}
 
Example 24
Source Project: maven-framework-project   Source File: Zip4j.java    License: MIT License 6 votes vote down vote up
/**
 * 示例2 创建压缩包添加文件到指定目录中进行压缩
 */
@Test
public void example2(){
	try {
           ZipFile zipFile = new ZipFile("src/main/resources/AddFilesDeflateComp.zip");
           ArrayList<File> filesToAdd = new ArrayList<File>();
           filesToAdd.add(new File("src/main/resources/sample.txt"));
           filesToAdd.add(new File("src/main/resources/zip4j.txt"));
           filesToAdd.add(new File("src/main/resources/zip4j-1.3.2.jar"));
            
           ZipParameters parameters = new ZipParameters();
           parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
            
           parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
           parameters.setRootFolderInZip("target/");

           zipFile.addFiles(filesToAdd, parameters);
       } catch (ZipException e) {
           e.printStackTrace();
       } 
}
 
Example 25
Source Project: maven-framework-project   Source File: Zip4j.java    License: MIT License 6 votes vote down vote up
/**
 * 示例3 添加文件夹到压缩包中
 */
@Test
public void example3(){
	try {
           
           ZipFile zipFile = new ZipFile("src/main/resources/AddFolder.zip");
           String folderToAdd = "src/main/resources";
        
           ZipParameters parameters = new ZipParameters();
            
           parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
           parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
           zipFile.addFolder(folderToAdd, parameters);
            
       } catch (ZipException e) {
           e.printStackTrace();
       }
}
 
Example 26
Source Project: maven-framework-project   Source File: Zip4j.java    License: MIT License 6 votes vote down vote up
/**
 * 示例5 创建分卷压缩包
 */
@Test
public void example5(){
	try {
         
           ZipFile zipFile = new ZipFile("src/main/resources/CreateSplitZipFile.zip");

           ArrayList<File> filesToAdd = new ArrayList<File>();
           filesToAdd.add(new File("src/main/resources/sample.txt"));
           filesToAdd.add(new File("src/main/resources/zip4j.txt"));
           filesToAdd.add(new File("src/main/resources/zip4j-1.3.2.jar"));
            
           ZipParameters parameters = new ZipParameters();
           parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
            
           parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
            
           zipFile.createZipFile(filesToAdd, parameters, true, 65536);
       } catch (ZipException e) {
           e.printStackTrace();
       }
}
 
Example 27
Source Project: Bats   Source File: ConfigPackage.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates an Config Package object.
 *
 * @param file
 * @throws java.io.IOException
 * @throws net.lingala.zip4j.exception.ZipException
 */
public ConfigPackage(File file) throws IOException, ZipException
{
  super(file);
  Manifest manifest = getManifest();
  if (manifest == null) {
    throw new IOException("Not a valid config package. MANIFEST.MF is not present.");
  }
  Attributes attr = manifest.getMainAttributes();
  configPackageName = attr.getValue(ATTRIBUTE_DT_CONF_PACKAGE_NAME);
  appPackageName = attr.getValue(ATTRIBUTE_DT_APP_PACKAGE_NAME);
  appPackageGroupId = attr.getValue(ATTRIBUTE_DT_APP_PACKAGE_GROUP_ID);
  appPackageMinVersion = attr.getValue(ATTRIBUTE_DT_APP_PACKAGE_MIN_VERSION);
  appPackageMaxVersion = attr.getValue(ATTRIBUTE_DT_APP_PACKAGE_MAX_VERSION);
  configPackageDescription = attr.getValue(ATTRIBUTE_DT_CONF_PACKAGE_DESCRIPTION);
  String classPathString = attr.getValue(ATTRIBUTE_CLASS_PATH);
  String filesString = attr.getValue(ATTRIBUTE_FILES);
  if (configPackageName == null) {
    throw new IOException("Not a valid config package.  DT-Conf-Package-Name is missing from MANIFEST.MF");
  }
  if (!StringUtils.isBlank(classPathString)) {
    classPath.addAll(Arrays.asList(StringUtils.split(classPathString, " ")));
  }
  if (!StringUtils.isBlank(filesString)) {
    files.addAll(Arrays.asList(StringUtils.split(filesString, " ")));
  }

  ZipFile zipFile = new ZipFile(file);
  if (zipFile.isEncrypted()) {
    throw new ZipException("Encrypted conf package not supported yet");
  }
  File newDirectory = Files.createTempDirectory("dt-configPackage-").toFile();
  newDirectory.mkdirs();
  directory = newDirectory.getAbsolutePath();
  zipFile.extractAll(directory);
  processPropertiesXml();
  processAppDirectory(new File(directory, "app"));
}
 
Example 28
Source Project: Bats   Source File: AppPackage.java    License: Apache License 2.0 5 votes vote down vote up
public static void createAppPackageFile(File fileToBeCreated, File directory) throws ZipException
{
  ZipFile zipFile = new ZipFile(fileToBeCreated);
  ZipParameters params = new ZipParameters();
  params.setIncludeRootFolder(false);
  zipFile.addFolder(directory, params);
}
 
Example 29
Source Project: AndroidZip   Source File: ZipManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 压缩文件或者文件夹
 *
 * @param targetPath          被压缩的文件路径
 * @param destinationFilePath 压缩后生成的文件路径
 * @param password            压缩加密 密码
 * @param callback            压缩进度回调
 */
public static void zip(String targetPath, String destinationFilePath, String password, IZipCallback callback) {
    if (!Zip4jUtil.isStringNotNullAndNotEmpty(targetPath) || !Zip4jUtil.isStringNotNullAndNotEmpty(destinationFilePath)) {
        if (callback != null) callback.onFinish(false);
        return;
    }
    ZipLog.debug("zip: targetPath=" + targetPath + " , destinationFilePath=" + destinationFilePath + " , password=" + password);
    try {
        ZipParameters parameters = new ZipParameters();
        parameters.setCompressionMethod(8);
        parameters.setCompressionLevel(5);
        if (password.length() > 0) {
            parameters.setEncryptFiles(true);
            parameters.setEncryptionMethod(99);
            parameters.setAesKeyStrength(3);
            parameters.setPassword(password);
        }
        ZipFile zipFile = new ZipFile(destinationFilePath);
        zipFile.setRunInThread(true);
        File targetFile = new File(targetPath);
        if (targetFile.isDirectory()) {
            zipFile.addFolder(targetFile, parameters);
        } else {
            zipFile.addFile(targetFile, parameters);
        }
        timerMsg(callback, zipFile);
    } catch (Exception e) {
        if (callback != null) callback.onFinish(false);
        ZipLog.debug("zip: Exception=" + e.getMessage());
    }
}
 
Example 30
/**
 * This method extracts all entries of a zip-file.
 * 
 * @param zipsource Path of the zip-file.
 * @param target Path of the extracted files.
 * @return True if successfully extracted.
 */
public boolean unzip(String zipsource, String target) {
	boolean result = true;
	try {
		ZipFile zipFile = new ZipFile(zipsource);
		setCharset(zipFile);
		zipFile.extractAll(target);
	} catch (Throwable e) {
		result = false;
		logError(e.getMessage());
	}
	return result;
}